小编phi*_*hil的帖子

如何初始化模板中的成员数组

我想有一个数组的长度取决于我的模板的参数,但我不断得到"预期的常量表达式"错误.

enum MyEnum
{
    FIRST,
    OTHER
};

template<MyEnum e> 
struct MyTemplate
{
    static const int arrSize;
    int myArr[arrSize];            // error C2057: expected constant expression
    // int myArr[e == FIRST ? 4 : 10]; // works, but isn't very readable...
};

template<>
const int MyTemplate<FIRST>::arrSize = 4;

template<>
const int MyTemplate<OTHER>::arrSize = 10;
Run Code Online (Sandbox Code Playgroud)

我必须使用的编译器不支持constexpr,或任何其他C++ 11功能,我也不能将数组大小作为模板参数传递.

编辑:我也一定不能用new.

谢谢

c++ templates allocation const

0
推荐指数
1
解决办法
45
查看次数

标签 统计

allocation ×1

c++ ×1

const ×1

templates ×1