我在网站上看到该声明
template <int x>
int func() {
return x;
}
有效,但以下无效
template <double x>
double func() {
return x;
}
为什么第一个是模板函数的合法声明,而第二个不是?
最佳答案
它无效,因为它不是整型。非类型模板参数有一定的限制,这就是其中之一,它说......
Floating-point numbers and class-type objects are not allowed as nontype template parameters.
template <double VAT> // ERROR: floating-point values are not
double process(double v) { // allowed as template parameters
return v * VAT;
}
template <std::string name> // ERROR: class-type objects are not
class MyClass { // allowed as template parameters
/* ... */
};
以上引自C++ Templates 。我不为此获得任何荣誉。
根据我的理解,它们对于模板初始化无效的原因是因为像 float 和 double 这样的类型在 C++ 中没有定义的实现。所以当像
这样的模板template <double VAT> double process(double v);
用两个不同的 double 值初始化为
template <(double) 2/3> double process(2.3)
template <(double) 1/3> double process(2.4);
由于双非类型,它们可能没有相同的位表示,这会让编译器感到困惑。
关于c++ - 为什么浮点类型对于模板函数来说是无效的模板参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11806091/