2017-02-15 94 views
2

我需要爲我的類獲取2個類型參數:T1,它是一個具有模板的類,T2是T1模板的參數。在我的情況下,一個頂點類型(有2個,一個從另一個繼承),數據類型頂點存儲(在我的情況下名稱/ ID)。嵌套模板(即模板<typename T <typename templateArgumentFor_T >>)

我希望能夠寫出這樣的事:

template < typename VertexType < typename VertexIDType > > 

(它給我的錯誤:C2143語法錯誤:缺少「」前「<」)

所以我的班會是這樣的:(「名單」是我的一個鏈表(不std的)實現)

class Graph 
{ 
public:  
    Graph(const List<VertexType<VertexIDType>>& verticesList); 
    VertexType<VertexIDType>& getVertexByID(const VertexIDType& ID) const; 

private:  
    List<VertexType<VertexIDType>> vertices; 
}; 

我也試過template <typename VertexType, typename VertexIDType> 後來我在功能Graph(const List<VertexType<VertexIDType>>& verticesList); 遇到錯誤(C2947預期「>」終止模板參數列表,找到「<」)

template < typename VertexType < template <typename VertexIDType> > >

(這也給我錯誤C2143)

我真的是那種試圖自己決定一切的人,但這個越來越沮喪。我找不到一個答案,我明白如果/如何在我的代碼中實現。 我現在已經完成了OOP(C++)課程。我有一些模板的經驗。我寫了模板,可以成功地獲得1或2個參數,但沒有像這樣。

請幫我解決這個問題,最好儘可能優雅:)

謝謝。

回答

3

您可以使用模板模板參數:

template <template <typename> class VertexType, typename VertexIDType> 
class graph; 

graph<MyVertexType, MyVertexIDType> //usage 

或者你可以花一點點的類型和提取部分專業化ID類型:

template <typename Vertex> 
class graph; 

template <template <typename> class VertexType, typename VertexIDType> 
class graph <VertexType<VertexIDType>> { 
    //... 
}; 

graph<MyVertexType<MyVertexIDType>> //usage 
+0

非常感謝! –

1

TartanLlama的回答是一個很好的您提問的問題,但您可能需要稍微改變您的方法。如果你需要一個VertexType必須定義一個typedef VertexIDType,那麼你可以這樣寫:

template <class VertexType> 
class Graph 
{ 
public:  
    Graph(const List<VertexType>& verticesList); 
    typedef typename VertexType::VertexIDType VertexIDType; 
    VertexType& getVertexByID(const VertexIDType& ID) const; 

private:  
    List<VertexType> vertices; 
}; 

注意typename中的typedef VertexIDType。有必要說「這個名字必須是一個類型而不是變量」。

假設您目前VertexType的模板上VertexIDType

template <classname VertexIDType> 
struct VType1 { 
    double stuff; // Or whatever you have in your vertex 
}; 

您需要將其更改爲:

template <classname VertexIDType> 
struct VType1 { 
    double stuff; 
    typedef VertexIDType VertexIDType; // Provide a typedef for VertexIDType. 
}; 

這類似於標準庫中所採用的方法,每一種類型的凡是一個集裝箱有一個typedef爲value_type

+0

您可以詳細說明「typedef typename」的定義嗎?我沒有真正理解語法。什麼是第一個「VertexIDType」代表?它在「VertexType」定義(我猜你會期望它,因此是「::」)中的外觀如何?什麼是第二個「VertexIDType」代表? 另外,在我的代碼中「VertexIDType」沒有在「VertexType」中定義。它只是在那裏表示爲模板參數。這不是一堂課。它代表int,long,char,string等或非標準類型(類),如果將來需要的話。 –

+0

所以我們的想法是改變'VertexType',以便在其中定義'VertexIDType' *。我的編輯有幫助嗎? –

+0

@DrorFelman:VertexIDType是VertextType的模板參數嗎?如果是這樣,那就更容易了。 –

相關問題