相关疑难解决方法(0)

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

当我尝试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++ generics floating-point templates

107
推荐指数
7
解决办法
5万
查看次数

constexpr函数参数作为模板参数

我正在玩一些使用c ++ 11的玩具代码来弄清楚事情是如何运作的.在此期间,我遇到了以下问题,简化为:

template <int x, int y>
class add {
public:
    static constexpr int ret = x + y;
};

constexpr int addFunc(const int x, const int y) {
    return add<x,y>::ret;
}

int main() {
    const int x = 1;
    const int y = 2;
    cout << add<x,y>::ret << endl; // Works
    cout << addFunc(1,2) << endl;  // Compiler error
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用GCC 4.8.1并且输出为:
'x'不是模板参数中的常量表达式,用于'int'类型
'y'不是类型'int'的模板参数中的常量表达式

我试图计算的两种方式之间究竟有什么区别add::ret?这两个值都应该在编译时可用.

c++ constexpr c++11

22
推荐指数
4
解决办法
1万
查看次数

标签 统计

c++ ×2

c++11 ×1

constexpr ×1

floating-point ×1

generics ×1

templates ×1