为什么我不能使用浮点值作为模板参数?

新手上路,请多包涵

当我尝试使用 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 许可协议

阅读 898
2 个回答

当前的 C++ 标准不允许将 float (即实数)或字符串文字用作 _模板非类型参数_。您当然可以使用 floatchar * 类型作为普通参数。

也许作者正在使用不遵循当前标准的编译器?

原文由 anon 发布,翻译遵循 CC BY-SA 3.0 许可协议

从 C++20 开始,这是 可能的

这也给出了原始问题的答案:

 Why can't I use float value as a template parameter?

因为还没有人在标准中实现它。没有根本原因。

在 C++20 中,非类型模板参数现在可以是浮点数甚至是类对象。

对类对象有一些要求(它们必须是 文字类型)并满足一些其他要求以排除用户定义的运算符 == ( 详细信息)等病态情况。

我们甚至可以使用 auto

 template <auto Val>
struct Test {
};

struct A {};
static A aval;
Test<aval>  ta;
Test<A{}>  ta2;
Test<1.234>  tf;
Test<1U>  ti;

请注意,GCC 9(和 10)实现了类非类型模板参数, 但还没有实现 floats

原文由 Andreas H. 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题