2017-04-26 29 views
1

我已經用數據數組(一些常量靜態,一些可變)和訪問器方法生成了配置文件。問題是,現在有一種數據類型將被模板化,但我無法讓編譯器接受它。模板類中的數組定義

模板類型是非pod,但默認可構造。

使用的定義是在cpp文件中,但由於我不知道模板類型,而代碼正在生成,我不能再這樣做了。

I.e.我想類似如下(如果我能更好,但頭外面的定義)

template<typename T> 
class LargeConfig : 
{ 
public: 
    // methods 
private: 
    static const POD1 POD_ONES[]; 
    T ManyTs[]; 
}; 

template<typename T> 
static const POD1 LargeConfig<T>::POD_ONES[] = 
{ 
    { 0U, 1U}, // instance 1 
    { 1U, 1U}, // instance 2 
    ... 
}; 

template<typename T> 
T LargeConfig<T>::ManyTs[] = 
{ 
    T(), // instance 1 
    T(), // instance 2 
    ... 
}; 

目前我得到「存儲類可能不會在這裏指定」爲POD_ONES定義和「非靜態數據成員可能不會在其類之外定義爲「ManyTs」。

但肯定有一定的方法來創建模板化的非平凡的數組在c + +中的類?到目前爲止,我只找到了模板類型是整數類型的例子。

+0

'POD1'在範圍內嗎?只要定義了錯誤,我就不會收到錯誤。 – NathanOliver

+0

@NathanOliver:恩。非常感謝。在更改代碼時,我創建了靜態POD結構const的一個成員。顯然,這導致我的嵌入式編譯器將它視爲非POD並給出了上面的錯誤消息。沒有const成員,POD_ONES部分就可以工作。 – Troels

回答

1

首先,ManyTs未聲明爲static,因此有關nonstatic data member defined outside of class的錯誤。

然後,不要把關鍵字static當你定義static成員:

template<typename T> 
class LargeConfig 
{ 
public: 
    // methods 
private: 
    static const POD1 POD_ONES[]; 
    static T ManyTs[]; 
}; 

template<typename T> 
const POD1 LargeConfig<T>::POD_ONES[] = 
{ 
    { 0U, 1U}, // instance 1 
    { 1U, 1U}, // instance 2 
}; 

template<typename T> 
T LargeConfig<T>::ManyTs[] = 
{ 
    T(), // instance 1 
    T() // instance 2 
}; 

我編了sample demo(設置公衆可以快速訪問它們的static數據成員)

0

嘗試在這裏編譯你的代碼(g ++ 5.4)我在第7行得到了一個語法錯誤。糾正我們得到的結果:糾正我們得到的結果:

templates.cpp:16:44: error: ‘static’ may not be used when defining (as opposed to declaring) a static data member [-fpermissive] 
static const POD1 LargeConfig<T>::POD_ONES[] = 
              ^
templates.cpp:23:26: error: ‘T LargeConfig<T>::ManyTs []’ is not a static data member of ‘class LargeConfig<T>’ 
T LargeConfig<T>::ManyTs[] = 
         ^
templates.cpp:23:26: error: template definition of non-template ‘T LargeConfig<T>::ManyTs []’ 

第一條消息與this problem有關。您不能使用靜態來定義數據類型,只能用於聲明。

通過簡單地使ManyTs成員變爲靜態,可以糾正最後一個錯誤。

的代碼就變成了這樣的事情:

class POD1 { 

}; 

template<typename T> 
class LargeConfig 
{ 
public: 
    // methods 
private: 
    static const POD1 POD_ONES[]; 
    static T ManyTs[]; 
    T ManyTsAgain[10]; 
}; 

template<typename T> 
const POD1 LargeConfig<T>::POD_ONES[] = 
{ 
    { 0U, 1U}, // instance 1 
    { 1U, 1U}, // instance 2 
}; 

template<typename T> 
T LargeConfig<T>::ManyTs[] = 
{ 
    T(), // instance 1 
    T(), // instance 2 
}; 

int main() { 
    LargeConfig<int> obj1; 
    LargeConfig<POD1> obj2; 

    return 0; 
} 
1

正如自己所指出的,你有2個問題,讓我先從第二個。

ManyTs被定義爲LargeConfig的常規成員,這意味着它應該在您的類的構造函數中初始化。舉個例子:

template<typename T> 
LargeConfig<T>::LargeConfig() 
: ManyTs 
    { T(), // instance 1 
     T(), // instance 2 
     ... 
    } 
{} 

的第一個問題是很難猜測,因爲我設法與下面術後第一天

struct POD1 
{ 
    POD1(unsigned, unsigned); 
    unsigned _1{}; 
    unsigned _2{}; 
}; 

的定義編譯它我懷疑你要麼不包括的類或某事儘管如此,其他人對這個班級也是錯誤的,因爲我們看不到它,所以很難說。