C++ 如何为我自己的集合类启用括号内的初始值设定项列表?
给定此示例类:C++ 如何为我自己的集合类启用括号内的初始值设定项列表?,c++,collections,c++11,std,initializer-list,C++,Collections,C++11,Std,Initializer List,给定此示例类: 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; // ye
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;
}
};
模板
类示例容器
{
私人:
std::map\u对象;
整数和;
公众:
示例容器()
:_objects(),_sum(0)
{
}
无效添加(T obj,int Add)
{
_objects[obj]=add;//是的,这很糟糕,但这只是一个例子。
_总和+=相加;
}
};
需要什么才能像这样使用它:
ExampleContainer<char*> _rarities =
{
{ "One", 600 },
{ "Two", 200 },
{ "Three", 50 },
{ "Four", 10 },
{ "Five", 1 },
};
ExampleContainer\u稀有=
{
{“一”,600},
{“两个”,200},
{“三”,50},
{“四”,10},
{“五”,1},
};
我知道这一定是有可能的,因为我已经可以像那样初始化std::map了
提前感谢您的回答。只需将接受
std::initializer\u列表的构造函数添加到ExampleContainer
类:
ExampleContainer(std::initializer_list<typename std::map<T, int>::value_type> l)
:
_objects(l)
{
}
ExampleContainer(标准::初始值设定项\u列表l)
:
_对象(l)
{
}
每次使用大括号初始化对象时,都会调用此函数,如本例所示:
ExampleContainer<char*> _rarities =
{
...
};
ExampleContainer\u稀有=
{
...
};
这样,大括号内的每个条目都将成为初始值设定项列表的一个元素
由于此处初始值设定项列表的基本类型是std::map::value\u 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.
};
ExampleContainer\u稀有=
{
{“一”,600},//这些实体中的每一个都会导致
{“Two”,200},//类型为的临时对象:
{“三”,50},//std::pair
{“Four”,10},//这将成为初始值设定项的一个元素
{“五”,1},//构造函数收到的列表。
};
还要注意的是,从字符串文字到char*
的转换在C++03中是不推荐的,在C++11中是无效的(字符串文字在C++11中具有类型char const[]
)。因此,您可能希望为变量\rarities
指定类型ExampleContainer
(C数组类型衰减为指针类型)
更新:
正如@LightnessRacesInOrbit在评论中正确指出的那样,如果您不打算在容器中只使用字符串文字,那么这种方法是危险的(这是我从您的示例中假设的,但事实上没有任何暗示)。最好改用std::string
(因此您应该将\u rarities
声明为ExampleContainer
)。感谢您提供了准确而详尽的答案。不用担心,实际上我使用带有int/enum的ExampleContainer,但出于示例考虑,我更可能使用char*=)的std::string
。您不能真正“存储”C字符串,如果您尝试,您可能会有严重的所有权错误。@LightnessRacesinOrbit:这一点很好。但只要他只使用字符串文字就可以了,对吗?@LightnessRacesinOrbit:同意。答案中将提到它。不仅C++03中不推荐使用字符串文字(不是const char*
!)的转换,而且C++11中也没有这种转换。