请考虑以下代码
template <typename T, T one>
T exponentiel(T val, unsigned n) {
T result = one;
unsigned i;
for(i = 0; i < n; ++i)
result = result * val;
return result;
}
int main(void) {
double d = exponentiel<double,1.0>(2.0f,3);
cout << d << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器告诉我这个调用'exponentiel(float,int)'没有匹配函数
为什么?
奇怪的是exponentiel与int一起工作.
Jam*_*lis 10
问题是,与T one和1.0模板参数列表.
您不能拥有浮点类型的非类型模板参数,也不能将浮点值作为模板参数传递.这是不允许的(据我所知,没有很好的理由为什么不允许).
这里的g ++错误信息是无益的.Visual C++ 2010在使用模板的行上报告以下内容main:
error C2993: 'double' : illegal type for non-type template parameter 'one'
Run Code Online (Sandbox Code Playgroud)
line 13: error: expression must have integral or enum type
double d = exponentiel<double,1.0>(2.0f,3);
^
line 2: error: floating-point template parameter is nonstandard
template <typename T, T one>
^
Run Code Online (Sandbox Code Playgroud)