为什么不能使用float值作为模板参数? [英] Why can't I use float value as a template parameter?

查看:839
本文介绍了为什么不能使用float值作为模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用 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 << "\n sum of integer is "<<gcInteger.returnVal();
    cout << "\n sum of float is "<<gcFlaot.returnVal();

    return 0;       
}

错误: b

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?

这篇关于为什么不能使用float值作为模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆