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?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
