如何定义用枚举模板化的容器

时间:2017-12-07 17:05:02

标签: c++ templates vector

我需要创建一个容器,该容器包含整数并使用枚举模板化。

 enum Color{R,G,B};

 template<class Color C,//class before color will be removed
 template <class, class = allocator<int>> class Container>
 class MyClass
 {
    Container<int> buffer;
 }

我需要创建向量并列出它。类似的东西:

 MyClass<Color::R, std::list> mbs
 MyClass<Color::G, std::vector> mbs

 //wrong number of template arguments (1, should be 2)
 MyClass<Color C, vector> v1;

 //for contaner
 Container<int>::iterator nth = buffer.begin()

1 个答案:

答案 0 :(得分:2)

您正在寻找non-type template parameter

对于你的容器,它的定义如下:

template<Color C, 
         template<class, class = std::allocator<int>> class Container>
class MyClass{
   Container<int> buffer;
   // ...
};

您可以像这样创建一个实例:

MyClass<Color::R, std::vector> instance;

您可以像这样创建一个迭代器:

typename Container<int>::iterator iter = buffer.begin();

typename是必需的,因为iteratordependent name