例如,我想专门化一个类,让它有一个成员变量,它是一个 STL 容器,比如一个 vector 或一个列表,所以我需要这样的东西:
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
最佳答案
你要的是模板模板参数:
template <template <typename> class CollectionType, class ItemType>
class Test
{
public:
CollectionType<ItemType> m_collection;
};
我们在这里所做的是指定第一个模板参数,即 CollectionType
,是一个类型模板。因此,Test
只能用本身就是模板的类型实例化。
然而,正如@Binary Worrier 在评论中指出的那样,这不适用于 STL 容器,因为它们有 2 模板参数:一个用于元素类型,另一个用于元素类型用于管理存储分配的分配器(具有默认值)。
因此,您需要更改第一个模板参数,使其具有两个参数:
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 容器......
我的建议:请参阅 Greg Rogers 的回答以获得更好的方法:)!
关于c++ - 您可以使用 C++ 模板来指定集合类型和该类型的特化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/956658/