如何为我自己的集合类启用包含大括号的初始值设定项列表
How to enable brace enclosed initializer lists for my own collection class?
给定以下示例类:
template<typename T>
class ExampleContainer
{
private:
std::map<T, int> _objects;
int _sum;
public:
ExampleContainer()
: _objects(), _sum(0)
{
}
void Add(T obj, int add)
{
_objects[obj] = add; // yes this is bad, but it's an example.
_sum += add;
}
};
需要什么才能像这样使用它:
ExampleContainer<char*> _rarities =
{
{ "One", 600 },
{ "Two", 200 },
{ "Three", 50 },
{ "Four", 10 },
{ "Five", 1 },
};
我知道这一定是可能的,因为我已经可以初始化这样的std::map了。
提前感谢您的回答。
只需在ExampleContainer
类中添加一个接受std::initializer_list
的构造函数:
ExampleContainer(std::initializer_list<typename std::map<T, int>::value_type> l)
:
_objects(l)
{
}
每次使用大括号初始化对象时,都会调用它,如本例所示:
ExampleContainer<char*> _rarities =
{
...
};
这样,大括号中的每个条目都将成为初始值设定项列表的一个元素。
由于这里的初始值设定项列表的基础类型是std::map<T, int>::value_type
,因此该类型的临时对象将由您提供的值构造:
ExampleContainer<char*> _rarities =
{
{ "One", 600 }, // Each of these entires will cause the creation of
{ "Two", 200 }, // a temporary object of type:
{ "Three", 50 }, // std::pair<char* const, int>
{ "Four", 10 }, // that will become an element of the initializer
{ "Five", 1 }, // list received by the constructor.
};
另外请注意,从字符串文字到char*
的转换在C++03中是不赞成的,在C++11中是无效的(字符串文字在C++11中的类型为char const[]
)。因此,您可能希望将变量_rarities
的类型改为ExampleContainer<char const*>
(C数组类型衰减为指针类型)。
更新:
正如@LightnessRacesInOrbit在评论中正确指出的那样,如果你不打算在容器中只使用字符串文字,这种方法是危险的(这是我从你的例子中假设的,但事实上没有任何暗示)。最好使用std::string
(因此应该将_rarities
声明为ExampleContainer<std::string>
)。
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 将矩阵乘以我自己的输入的向量
- 如何正确包含我自己的标头?
- 如何使用我构建的库,而不会从源代码出错,但不为我自己的项目编译?
- 预期'while'或预期'}' 之前回答是,但我自己无法修复
- 为什么__builtin_popcount比我自己的比特计数功能慢?
- 在wxWidgets的事件中包含我自己的数据的最佳方法是什么?
- 如何在我自己的staticLib中使用staticLib
- 在我自己的堆栈中实现top的问题
- 尝试检查输入的文本与我自己的自定义答案
- 如何在我自己的类中重载"+"和"<<"运算符
- C++:我自己类的动态数组
- 如何在 C++ 中使用我自己的类中的库?
- 如何链接我自己的 .so 文件而不是操作系统捆绑包 .so 文件?
- 如何构建默认使用我自己的构建libc ++的clang?
- 访问另一个类(系统)的非静态字段,就好像它是我自己的字段一样 - 优雅地
- 试图用c++编写我自己的链表实现,在点击列表中的3个元素后编写segfault代码
- 如何将列表'node_ptr'转换为我自己的节点类型
- vector std::out_of_range 在我自己的模板类中(指向列表节点的指针向量),但我不明白为什么
- 如何为我自己的集合类启用包含大括号的初始值设定项列表