C++ 你会用C++;指定集合类型和该类型的专门化的模板?
例如,我想专门化一个类,使其具有一个成员变量,即stl容器,比如向量或列表,因此我需要如下内容:C++ 你会用C++;指定集合类型和该类型的专门化的模板?,c++,templates,collections,C++,Templates,Collections,例如,我想专门化一个类,使其具有一个成员变量,即stl容器,比如向量或列表,因此我需要如下内容: template <class CollectionType, class ItemType> class Test { public: CollectionType<ItemType> m_collection; }; 您需要的是一个模板参数: template <template <typename> class CollectionType,
template <class CollectionType, class ItemType>
class Test
{
public:
CollectionType<ItemType> m_collection;
};
您需要的是一个模板参数:
template <template <typename> class CollectionType, class ItemType>
class Test
{
public:
CollectionType<ItemType> m_collection;
};
但是等等,那也不行!实际上,CollectionType
正在等待另一个参数,分配器。。。现在有两种解决方案:
一,。强制使用特定分配器:
CollectionType<ItemType, std::allocator<ItemType> > m_collection
CollectionType m_集合
二,。将分配器的模板参数添加到类中:
template <template <typename,typename> class CollectionType,
class ItemType,
class Allocator = std::allocator<ItemType> >
class Test
{
public:
CollectionType<ItemType, Allocator> m_collection;
};
模板
课堂测试
{
公众:
集合类型m_集合;
};
正如您所看到的,您最终会遇到一些相当复杂的问题,在处理STL容器时,这些问题看起来非常复杂
我的建议是:请参阅格雷格·罗杰斯的答案,了解更好的方法:) 为什么不这样做呢
template <class CollectionType>
class Test
{
public:
CollectionType m_collection;
};
Test t = Test<vector<int> >();
t.m_collection = vector<int>();
添加typename是因为CollectionType尚未绑定到实际类型。因此,它无法查找值类型 Comeau online喜欢这样:
#include <vector>
template <template <class T, class A = std::allocator<T> > class CollectionType, class ItemType>
class Test
{
public:
CollectionType<ItemType> m_collection;
};
void foo()
{
using std::vector;
Test<vector,int> t = Test<vector, int>();
t.m_collection = vector<int>();
}
#包括
模板
课堂测试
{
公众:
集合类型m_集合;
};
void foo()
{
使用std::vector;
测试t=测试();
t、 m_collection=vector();
}
Good response:这种方法测试更通用,因为它甚至可以与非模板容器一起工作。我不确定我是否可以这样做,因为我需要编写一个返回Item类型对象的成员函数。例如,我不能做CollectionType::value\u type*advance()。@justinhj:为什么不能?为什么不能使用CollectionType::value_type?CollectionType::value_type test2Get();给出test3.cpp:30:error:expected`;'在“test2Get”之前,您需要在CollectionType::value\u type之前添加typename。在处理模板成员时,这是一个常见的错误。这很有效,我不太理解。这部分在做什么?这对我来说是不可编译的(VS2008),我想为vector上的分配器添加第二种类型,使模板声明为“template”。m_collection的声明后来变成了“CollectionType”+1,因为它指出了“模板参数”,谢谢:)关于模板参数的精彩教程,请参见“@BinaryWorrier,是的,我在实例化测试时也遇到了同样的错误。@Binary Worrier你完全正确,这就是你写答案时得到的结果“又快又脏”:-!我马上换。
template <template <typename,typename> class CollectionType,
class ItemType,
class Allocator = std::allocator<ItemType> >
class Test
{
public:
CollectionType<ItemType, Allocator> m_collection;
};
template <class CollectionType>
class Test
{
public:
CollectionType m_collection;
};
Test t = Test<vector<int> >();
t.m_collection = vector<int>();
typename CollectionType::value_type foo();
#include <vector>
template <template <class T, class A = std::allocator<T> > class CollectionType, class ItemType>
class Test
{
public:
CollectionType<ItemType> m_collection;
};
void foo()
{
using std::vector;
Test<vector,int> t = Test<vector, int>();
t.m_collection = vector<int>();
}