c++ - 使用 braced-init 初始化 std::shared_ptr<std::map<>>

标签 c++ c++11 shared-ptr stdmap list-initialization

我有以下 shared_ptrmap:

std::shared_ptr<std::map<double, std::string>>

我想使用 braced-init 来初始化它。可能吗?

我试过:

std::string s1("temp");
std::shared_ptr<std::map<double, std::string>> foo = std::make_shared<std::map<double, std::string>>(1000.0, s1);

但是在使用 Xcode 6.3 编译时出现以下错误:

/usr/include/c++/v1/map:853:14: Candidate constructor not viable: no known conversion from 'double' to 'const key_compare' (aka 'const std::__1::less<double>') for 1st argument

我尝试了第一个参数 (1000.0) 的其他变体,但没有成功。

有人能帮忙吗?

最佳答案

std::map 有一个初始化列表构造函数:

map (initializer_list<value_type> il,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());

我们可以很容易地使用这个构造函数创建一个 map :

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

关于c++ - 使用 braced-init 初始化 std::shared_ptr<std::map<>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36445642/

相关文章:

c++ - 使用 initialization_list 导致歧义的函数重载

c++ - 使用 boost 正则表达式时出现 shared_ptr 错误

c++ - 可能的 MSVC 编译器错误

c++ - 个别实例有效,但数组显示内存损坏

c++ - 如何使用 va_list 解决错误?

c++ - && 的优先级高于 ||

c++ - void() 和 void{} 有什么区别?

C++ Map 具有两个不同值的键

c++ - STL resize()的优点

c++ - 如何将现有对象的地址分配给智能指针?