c++ - 您可以使用 C++ 模板来指定集合类型和该类型的特化吗?

标签 c++ templates collections

例如,我想专门化一个类,让它有一个成员变量,它是一个 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/

相关文章:

c++ - OpenCV 中的随机顺序随机播放 cv::Mat

php - 我可以修改 'wc-template-functions.php' 文件中的 WooCommerce 函数,还是应该坚持使用 'functions.php' 文件进行此类修改?

function - 在 if 语句中使用函数 return 或在 go 模板中使用变量

java - Collections.sort() throws 比较方法违反了它的一般约定!异常(exception)

c++ - 在游戏中使用状态模式

c++ - 非模板类中的模板成员函数——如何定义和调用

C++ 删除语法

C++ 模板化成员函数作为另一个模板化类的接口(interface)

java - 为什么 AbstractList.removeRange 需要二次时间?

java - 哪些 java 集合接受添加空值?