簡體   English   中英

非集成靜態數據的類內初始化

[英]in-class initialization of non-integral static data

因此,我剛剛通過編譯器錯誤得知,數組的類內初始化無效(為什么?)。 現在,我想在模板類中初始化一些數組,但是不幸的是,內容取決於template參數。 壓縮的測試用例如下所示:

template<typename T>
struct A {
    T x;
    static const int len = sizeof(T);         // this is of course fine
    static const int table[4] = { 0, len, 2*len, 3*len };    //this not
}

任何想法如何拉出常量數組?

編輯:添加了'int's。

就像沒有模板時一樣; 將初始化放在類的聲明之外:

template<class T>
const int A<T>::table[4] = { 0, len, 2*len, 3*len };
 class Y
  { 
     const int c3 = 7; // error: not static 
     static int c4 = 7; // error: not const static const
     float c5 = 7; // error not integral
  };

那么為什么存在這些不便的限制呢? 通常在頭文件中聲明類,並且通常將頭文件包含在許多翻譯單元中。 但是,為避免復雜的鏈接器規則,C ++要求每個對象都有唯一的定義。 如果C ++允許對需要作為對象存儲在內存中的實體進行類內定義,則該規則將被打破。

有關更多詳細信息,請參見如何定義類內常量?


template <typename T, int index>
struct Table {
   static const len = sizeof(T);        
   static const value = len*index;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM