使用类模板的const静态变量初始化数组大小时出错

时间:2019-07-08 04:58:32

标签: c++ arrays size static-variables template-classes

template<typename T, typename C = vector<T>>
class stack{
    ...
    friend class stack_array;
};

template<typename T, typename C = vector<T>, typename K = stack<T,C>>
class stack_array{
     ...
     static const size_t max_elem;
     array<K, max_elem> store;
     ...
};

template<typename T, typename C = vector<T>, typename K = stack<T,C>>
const size_t stack_array<T,C,K>::max_elem = 10;

对于上述内容,我收到以下编译错误:

error: the value of ‘stack_array<T, C, K>::max_elem’ is not usable in a constant expression
array<K, max_elem> store;
                ^
note: ‘stack_array<T, C, K>::max_elem’ was not initialized with a constant expression
static const size_t max_elem;

我认为发生此错误是因为在模板类定义之后初始化了静态const变量max_elem。这种理解正确吗? 有没有一种方法可以解决此错误,而不必更改max_elem的当前用法?

1 个答案:

答案 0 :(得分:1)

我会说要就地初始化静态成员。

static const size_t max_elem = 10;

更多here

  

恒定静态成员如果整数或静态数据成员   枚举类型声明为const(并且不是volatile),它可以是   用初始化器初始化,其中每个表达式都是一个   常量表达式,就在类定义内:

struct X {
     const static int n = 1;
     const static int m{2}; // since C++11
     const static int k; }; 

     const int X::k = 3; // Only this needs to be defined
相关问题