当我尝试使用 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;
}
错误:
main.cpp: In function `int main()':
main.cpp:25: error: `float' is not a valid type for a template constant parameter
main.cpp:25: error: invalid type in declaration before ';' token
main.cpp:28: error: request for member `returnVal' in `gcFlaot',
which is of non-class type `int'
我正在阅读 Ron Penton 的 “游戏程序员的数据结构” ,作者通过了 float
,但是当我尝试它时它似乎没有编译。
原文由 yokks 发布,翻译遵循 CC BY-SA 4.0 许可协议
当前的 C++ 标准不允许将
float
(即实数)或字符串文字用作 _模板非类型参数_。您当然可以使用float
和char *
类型作为普通参数。也许作者正在使用不遵循当前标准的编译器?