how do you make a heterogeneous boost::map?(你如何制作异构 boost::map?)
问题描述
我想要一个具有同构键类型但具有异构数据类型的映射.
I want to have a map that has a homogeneous key type but heterogeneous data types.
我希望能够做一些类似(伪代码)的事情:
I want to be able to do something like (pseudo-code):
boost::map<std::string, magic_goes_here> m;
m.add<int>("a", 2);
m.add<std::string>("b", "black sheep");
int i = m.get<int>("a");
int j = m.get<int>("b"); // error!
我可以有一个指向基类的指针作为数据类型,但我宁愿没有.
I could have a pointer to a base class as the data type but would rather not.
我以前从未使用过 boost,但查看了fusion 库但不知道我需要做什么.
I've never used boost before but have looked at the fusion library but can't figure out what I need to do.
感谢您的帮助.
推荐答案
#include <map>
#include <string>
#include <iostream>
#include <boost/any.hpp>
int main()
{
try
{
std::map<std::string, boost::any> m;
m["a"] = 2;
m["b"] = static_cast<char const *>("black sheep");
int i = boost::any_cast<int>(m["a"]);
std::cout << "I(" << i << ")
";
int j = boost::any_cast<int>(m["b"]); // throws exception
std::cout << "J(" << j << ")
";
}
catch(...)
{
std::cout << "Exception
";
}
}
这篇关于你如何制作异构 boost::map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何制作异构 boost::map?
基础教程推荐
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
