[英]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
。 這種理解正確嗎? 有沒有辦法解決這個錯誤,而不必改變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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.