Why can#39;t I use float value as a template parameter?(为什么我不能使用浮点值作为模板参数?)
问题描述
当我尝试使用 float 作为模板参数时,编译器为这段代码哭泣,而 int 工作正常.
When I try to use float as a template parameter, the compiler cries for this code, while int works fine.
是不是因为我不能使用 float 作为模板参数?
Is it because I cannot use float as a template parameter?
#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 << "
sum of integer is "<<gcInteger.returnVal();
cout << "
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,但是当我尝试它时,它似乎无法编译.
I am reading "Data Structures for Game Programmers" by Ron Penton, the author passes a float, but when I try it it doesn't seem to compile.
推荐答案
当前的 C++ 标准不允许将 float(即实数)或字符串字面量用作 模板非- 类型参数.您当然可以使用 float 和 char * 类型作为普通参数.
The current C++ standard does not allow float (i.e. real number) or character string literals to be used as template non-type parameters. You can of course use the float and char * types as normal arguments.
也许作者使用的编译器不符合当前标准?
Perhaps the author is using a compiler that doesn't follow the current standard?
这篇关于为什么我不能使用浮点值作为模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能使用浮点值作为模板参数?
基础教程推荐
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
