2009-06-05 25 views
2

例如,我要專注一類有一個成員變量是一個STL容器,比如一個向量或列表,所以我需要的東西,如:您可以使用C++模板來指定集合類型和該類型的特化?

template <class CollectionType, class ItemType> 
class Test 
{ 
public: 
    CollectionType<ItemType> m_collection; 
}; 

所以我可以做:

Test t = Test<vector, int>(); 
t.m_collection<vector<int>> = vector<int>(); 

但這產生

test.cpp:12: error: `CollectionType' is not a template 

回答

9

爲什麼不這樣做呢?

template <class CollectionType> 
class Test 
{ 
public: 
    CollectionType m_collection; 
}; 

Test t = Test<vector<int> >(); 
t.m_collection = vector<int>(); 

如果您需要itemtype,您可以使用CollectionType::value_type

編輯:在回答你有關創建成員函數返回VALUE_TYPE問題,你做這樣的:

typename CollectionType::value_type foo(); 

您添加類型名稱,因爲CollectionType尚未綁定到一個實際的類型呢。所以沒有可以查找的value_type。

13

你想要的是一個模板,模板參數:

template <template <typename> class CollectionType, class ItemType> 
class Test 
{ 
public: 
    CollectionType<ItemType> m_collection; 
}; 

我們在這裏所做的是指定第一個模板參數,即CollectionType是一個類型模板。因此,Test只能使用本身是模板的類型實例化。

但是,由於@Binary Worrier在評論中指出,這將不適用於STL容器,因爲它們有模板參數:一個用於元素類型,另一個用於分配器類型用於管理存儲分配(具有默認值)。

因此,您需要更改第一個模板參數,以便它有兩個參數:

template <template <typename,typename> class CollectionType, class ItemType> 
class Test 
{ 
public: 
    CollectionType<ItemType> m_collection; 
}; 

別急,這將不會工作!確實,CollectionType等待另一個參數,分配器...所以現在你有兩個解決方案:

1。強制使用特定的分配器:

CollectionType<ItemType, std::allocator<ItemType> > m_collection 

2。爲分配器添加模板參數類:

template <template <typename,typename> class CollectionType, 
      class ItemType, 
      class Allocator = std::allocator<ItemType> > 
class Test 
{ 
public: 
    CollectionType<ItemType, Allocator> m_collection; 
}; 

所以你看,你最終的東西比較複雜,它似乎真的扭曲處理STL容器...

我的建議是:看到格雷格羅傑斯的答案更好的方法:)!

+0

這工作,我不太明白。 部分在做什麼? – justinhj 2009-06-05 16:15:04

+2

這不會爲我編譯(VS 2008),我會爲矢量上的分配器添加第二個類型,使模板聲明爲「template