2016-09-24 60 views
0
#pragma once 
//includes 
template<class RefType> 
class Foo 
{ 
public: 

template<> 
enum Foo<QString>::bar { //values A }; //LINE X 
template<> 
enum Foo<double>::bar { //values B }; 
template<> 
enum Foo<Kraken::Point3>::bar { //values C }; 
//functions 
}; //LINE Y 

編譯器給出了LINE X故障使用模板: '類' 型redifinition

error C2011: 'Foo<QString>': 'class' type redefinition 

與筆記

note: see declaration of 'Foo<QString>' LINE X 
note: note: see reference to class template instantiation 'Foo<RefType>'LINE Y 

我不明白,這個錯誤的根源錯誤,如果我對這個問題變得更加開明瞭,我會將問題的重新格式化,以便更清晰

+0

代碼中的「foo」和「bar」是什麼? – xinaiz

+0

班級名稱(Foo)和枚舉名稱(bar)的站點名稱 – brettmichaelgreen

+0

標題中的「第44集」是什麼意思? – tambre

回答

0

如果你想要有dif ferent enum的選擇爲類型,你應該與這些類型的專門的模板類:

template<class RefType> 
class Foo 
{ 
    //default enum if you want 
}; 

template<> 
class Foo<QString> 
{ 
    enum bar {Q1, Q2, Q3};  
}; 

template<> 
class Foo<double> 
{ 
    enum bar {d1, d2, d3};  
}; 

template<> 
class Foo<Kraken::Point3> 
{ 
    enum bar {K1, K2, K3};  
}; 

你的代碼看起來像要專門類模板的只是一些成員,但是這是不可能的C++。破解這一點,同時保留大部分的階級結構的

的一種方式,是一般類實現的公有繼承:

template<class Reftype> 
class FooImpl 
{ 
    RefType x; 
public: 
    void set_x(RefType val) {x=val;} 
    RefType get_x(void) {return x;} 
}; 

template<class RefType> 
class Foo : public FooImpl<Reftype> 
{ 

}; 

template<> 
class Foo<QString> : public FooImpl<QString> 
{ 
    enum bar {Q1, Q2, Q3};  
}; 

template<> 
class Foo<double> : public FooImpl<double> 
{ 
    enum bar {d1, d2, d3};  
}; 

template<> 
class Foo<Kraken::Point3> : public FooImpl<Kraken::Point3> 
{ 
    enum bar {K1, K2, K3};  
}; 

這樣你就不必重新定義所有的類成員只是因爲你想不同的枚舉專業化。