std::map
有一个初始化列表构造函数:
map (initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
我们可以轻松地使用此构造函数创建一个地图:
std::map<double,std::string> m1{{1000.0, s1}}
要在make_shared
中使用它,我们需要指定提供的initializer_list
的哪个实例:
auto foo = std::make_shared<std::map<double,std::string>>
(std::initializer_list<std::map<double,std::string>::value_type>{{1000.0, s1}})
这看起来很笨拙;但如果您需要经常使用它,您可以使用别名使其更整洁:
#include <string>
#include <map>
#include <memory>
std::string s1{"temp"};
using map_ds = std::map<double,std::string>;
using il_ds = std::initializer_list<map_ds::value_type>;
auto foo = std::make_shared<map_ds>(il_ds{{1000.0, s1}});
您可以选择定义一个模板函数来包装该调用:
#include <string>
#include <map>
#include <memory>
template<class Key, class T>
std::shared_ptr<std::map<Key,T>>
make_shared_map(std::initializer_list<typename std::map<Key,T>::value_type> il)
{
return std::make_shared<std::map<Key,T>>(il);
}
std::string s1{"temp"};
auto foo = make_shared_map<double,std::string>({{1000, s1}});
std::shared_ptr<std::map<double, std::string>> foo = std::make_shared<std::map<double, std::string>>(std::initializer_list<std::map<double, std::string>::value_type>{{1000.0, s1}});
- Piotr Skotnickivalue_type
的使用。我发现它只是typedef pair<const Key, Type>
。那我为什么需要它呢? - ksl