C++ 字面量

Author: yifei / Created: Nov. 12, 2017, 10:20 a.m. / Modified: Nov. 12, 2017, 10:21 a.m. / Edit


You can actually do this:

std::map<std::string, int> mymap = {{"one", 1}, {"two", 2}, {"three", 3}};

What is actually happening here is that std::map stores an std::pair of the key value types, in this case std::pair. This is only possible because of c++11's new uniform initialization syntax which in this case calls a constructor overload of std::pair. In this case std::map has a constructor with an std::intializer_list which is responsible for the outside braces.

So unlike python's any class you create can use this syntax to initialize itself as long as you create a constructor that takes an initializer list (or uniform initialization syntax is applicable)


有任何问题可以发邮件到 kongyifei (at) gmail.com 讨论