当我尝试float用作模板参数时,编译器会为此代码而烦恼,同时int工作正常.
是因为我不能float用作模板参数吗?
#include<iostream>
using namespace std;
template <class T, T defaultValue>
class GenericClass
{
private:
T value;
public:
GenericClass()
{
value = defaultValue;
}
T returnVal()
{
return value;
}
};
int main()
{
GenericClass <int, 10> gcInteger;
GenericClass < float, 4.6f> gcFlaot;
cout << "\n sum of integer is "<<gcInteger.returnVal();
cout << "\n sum of float is "<<gcFlaot.returnVal();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:
main.cpp: In function `int main()':
main.cpp:25: error: `float' is not a …Run Code Online (Sandbox Code Playgroud) C++模板的第4.3节 声明"不能使用浮点文字(和简单的常量浮点表达式)作为模板参数具有历史原因."
同样的,
$ 14.1/7状态 - "非类型模板参数不应声明为具有浮点,类或void类型.[示例:
template<double d> class X; // error
template<double* pd> class Y; // OK
template<double& rd> class Z; // OK"
Run Code Online (Sandbox Code Playgroud)
上述引文中正在讨论的历史原因是什么?
看看为什么Y和Z有效但不是X,整个挑战与浮动类型的非类型模板参数是否与指针/引用有关?
为什么模板非类型参数不能是类类型?