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

Error initializing array size using const static variable of class template

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;

我推测此错误发生是因为静态常量变量 max_elem 在模板 class 定义之后初始化。这种理解是否正确? 有没有办法在不必更改 max_elem 的当前用法的情况下解决此错误?

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

static const size_t max_elem = 10;

更多here.

Constant static members If a static data member of integral or enumeration type is declared const (and not volatile), it can be initialized with an initializer in which every expression is a constant expression, right inside the class definition:

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