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

how to define container templated with enum

本文关键字:枚举 何定义 定义      更新时间:2023-10-16

我需要创建一个容器,该容器可容纳整数并用枚举模板。

 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()

您正在寻找非类型模板参数

对于您的容器,它将像这样定义:

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是必需的,因为iterator是依赖的名称