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
?
我会说要就地初始化静态成员。
static const size_t max_elem = 10;
这里更多。
常量静态成员如果将整数或枚举类型的静态数据成员声明为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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句