c++ - 在 std::map<..., boost::any> 中初始化子图

标签 c++ c++11 dictionary boost

初始化 std::map<std::string, boost::any> 时, 值 boost::any确实可以接受任何类型的值,包括 std::map秒。但是,首先需要明确定义它们,例如,

#include <map>
#include <boost/any.hpp>
int main() {
  std::map<std::string, boost::any> a = {{"y", 2}};

  std::map<std::string, boost::any> any = {
    {"hh", 4},
    {"g", a}  // alright
  };
}

暗中尝试同样的事情,例如,

#include <map>
#include <boost/any.hpp>
int main() {
  std::map<std::string, boost::any> any = {
    {"hh", 4},
    {"g", {{"y", 2}}}  // mööp
  };
}

导致编译错误

error: could not convert ‘{{"hh", 4}, {"g", {{"y", 2}}}}’ from ‘<brace-enclosed initializer list>’ to ‘std::map<std::__cxx11::basic_string<char>, boost::any>’

怎么了?有没有办法将初始化放入一条语句中?

最佳答案

嗯,编译器不知道你的初始化列表最终应该变成什么类型​​。

给他一些帮助:

#include <map>
#include <boost/any.hpp>

using namespace std;

int main() {
  using StringToAny = std::map<std::string, boost::any>;
  StringToAny any = {
    {"hh", 4},
    {"g", StringToAny{{"y", 2}}}  // jippie!
  };
}

问题已解决。

关于c++ - 在 std::map<..., boost::any> 中初始化子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060790/

相关文章:

python - 将数据转储并加载到 JSON 中

python - 更Pythonic的方式来做到这一点?

c++ - 将 strcmp C/C++ 用于 Arduino 时的数字通配符

c++ - std::thread 不是全局变量,但在到达创建它的函数的末尾时不会超出范围?

QML TreeView 的 C++ 模型

c++ - 带有 move 语义的源函数和汇函数的签名

c++ - 基类型为函数引用时右值引用重载

python-3.x - 将字典嵌套在另一个字典中,按 Pandas Dataframe 中的值进行分组

c++ - 如何从 wow64 进程中检索特定内核对象的 64 位地址

c++ - 删除重复项和对 vector 进行排序的最有效方法是什么?