使用模板化类型指定模板化类型的类型

Specifying the type of a templated type with a templated type

本文关键字:类型      更新时间:2023-10-16

当我想用模板化类型定义向量的模板类型时会发生什么?我有一个类Customer,它是模板化的,这样构造函数就可以接受类型为vector<T>的参数。现在,我想实例化一个Customer类型的全局Vector,并发现自己想要键入vector<Customer<Customer<Customer<etc<etc>>>>>

我知道这可能是一个中午的问题,但我很想对我所处的这个小困境有一个简洁的解释。

提前感谢。。。

如果您想要一个特定类型的Customervector,那么一切都很简单:

template < typename T >
class Customer
{
public:
  Customer( std::vector< Customer< T > > vec );
}
std::vector< Customer<CustomerType> > v;

std::vector< Customer<CustomerType>* > v;

但是,如果您想要客户模板的不同实例,那么除了为类定义一些公共基础并存储它之外,没有其他方法:

class CustomerBase 
{ 
   /* common functionality */
};
template < typename T > 
class Customer : public CustomerBase
{
}
std::vector< CustomerBase* > v;
v.push_back( Customer< TypeA >() );
v.push_back( Customer< TypeB >() );