[英]How to initialize a member array in a template
我想拥有一个长度取决于我的模板参数的数组,但是我不断收到“期望的常量表达式”错误。
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;
我必须使用的编译器不支持constexpr
或任何其他C ++ 11功能,并且我也无法将数组大小作为模板参数传递。
编辑:我也一定不能使用new
。
谢谢
在这种情况下,我将添加一个函数get_array_size<e>()
。 由于您说自己没有constexpr,所以仍然有不错的可能性:
//I call this a pseudo-template-function, but there's probably better names
template<MyEnum> struct GetArraySize; //compiler error for default
template<> struct GetArraySize<FIRST> {static const int value=4;};
template<> struct GetArraySize<OTHER> {static const int value=10;};
template<MyEnum e>
struct MyTemplate
{
static const int arrSize = GetArraySize<e>::value;
int myArr[arrSize];
};
我们在这里重新发明轮子吗? 枚举是编译时间常数 。 只要这样做:
enum MyEnum
{
FIRST = 4,
OTHER = 10
};
template<MyEnum e>
struct MyTemplate
{
int myArr[e];
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.