【发布时间】:2013-07-06 20:27:50
【问题描述】:
我想将模板参数传递给函数调用,并将返回值用作数组的大小,即
constexpr int myPow(int a, int b){
int result = 1;
for(int i=0;i<b;i++)
result *= a;
return result;
}
template <int N>
class testClass{
public:
testClass(){}
int array[myPow(2,N)];
};
int main(){
testClass<3> A;
return 0;
}
编译器错误:
~ $ g++-4.6 test.cpp -std=gnu++0x
test.cpp: In function ‘constexpr int myPow(int, int)’:
test.cpp:6:1: error: body of constexpr function ‘constexpr int myPow(int, int)’ not a return-statement
test.cpp: At global scope:
test.cpp:12:23: error: array bound is not an integer constant before ‘]’ token
知道如何解决这个问题吗?
【问题讨论】:
-
您的函数不能超过一个
return ...;(C++14 之前),它只使用编译时工具,否则它不会返回编译时常量。 -
发布相关代码(即
myPow中的代码和最小完整的testClass,以及实际的编译器错误。 -
你真的前向声明了 myPow() 吗?在
testClass中使用它时是否知道它的函数原型? -
我添加了整个“工作”代码。
-
好吧,这就是克里斯所说的。在 C++11 中,您的
constexpr函数不能超过一个return语句。编译器错误消息已经表明这一点。