gpt4 book ai didi

c++ - 如何使用枚举定义容器模板

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:19 25 4
gpt4 key购买 nike

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

 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;
}

我需要创建 vector 并从中列出。像这样的东西:

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

最佳答案

您正在寻找 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

关于c++ - 如何使用枚举定义容器模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47700206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com