由于constexpr应该保证一个函数只包含编译时常数,并且在编译时进行评估(至少我认为它是这样),我以为可能是这个问题的解决方案.
所以我想出了这个:
template <class T,T VALUE> void f() {}
//first i tried this:
template <class T> auto get_f(T t) -> decltype( &f<T,t> ) { return f<T,t>; }
//second try:
template <class T> constexpr void (&get_f( T t ))() { return f<T,t>; }
int main()
{
get_f(10)(); //gets correct f and calls it
}
第一个版本生成以下错误:
error: use of parameter 't' outside function body
这真的很混乱,因为在拖尾返回类型的decltype语句中使用参数应该可以吗?
第二个版本生成以下错误:
error: invalid initialization of non-const reference of type 'void (&)()'
from an rvalue of type '<unresolved overloaded function type>'
这是有点混乱,因为我完全符合f在get_f.
我会期待这种错误消息,如果我没有constexpr.那么我对某个constexpr做了什么错误的了解,还是GCC对这种情况有缺陷呢?
我正在使用GCC 4.6.2
解决方法
Since constexpr should guarantee that a function only contains compile
time constants,and is evaluated at compile time (at least thats what
i think it does),i thought it might be the solution for this issue.
constexpr函数可以在常量表达式上下文中使用,但不限于此.在这方面,它们与元函数和常规函数不同.考虑返回一个整数的后继的问题:
// Regular function
int f(int i)
{ return i + 1; }
// Regular Metafunction
template<int I>
struct g {
static constexpr auto value = I + 1;
};
// constexpr function
constexpr int h(int i)
{ return i + 1; }
// Then...
{
// runtime context: the Metafunction can't be used
int i;
std::cin >> i;
f(i); // Okay
g<i>::value; // Invalid
h(i); // Okay
// compile time context: the regular function can't be used
char a[f(42)]; // Invalid
char b[g<42>::value]; // Okay
char c[h(42)]; // Okay
}
constexpr有其他用法(例如构造函数),但是当涉及到constexpr函数时,这就是它的要点:一些函数在运行时和常量上下文都应该可用,因为两者都有一些计算.可以计算i 1是否是编译时常数或从std :: cin中提取.
这意味着在一个constexpr函数的内部,参数本身不是常量表达式.所以你试图是不可能的.您的功能无法处理
int i; std::cin >> i; get_f(i); // what's the return type?
违规发生在这里:
constexpr auto get_f(T t) -> decltype( &f<T,t> ) // <-
由于t根据语言的规则不是一个常量表达式(无论什么,即使实际上只传递常量表达式),它也不能作为f的第二个模板参数出现.
(在较大的图片中,这意味着不,不能使用函数模板中的参数推导来方便地将非类型参数传递给类模板.)