你如何让一个异构的boost ::地图? [英] how do you make a heterogeneous boost::map?
本文介绍了你如何让一个异构的boost ::地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想有一个地图,具有均匀的密钥类型,但异构数据类型。
我希望能够像做(假code):
的boost ::地图<的std ::字符串,magic_goes_here>米;
m.add&所述; INT&GT(一,2);
m.add<标准::字符串>(B,害群之马);INT I = m.get&所述; INT&GT(一);
诠释J = m.get&所述; INT&GT(B); //错误!
我能有一个指向基类作为数据类型,但宁可不要。
我从来没有使用升压之前,但已经看过融合库,但无法弄清楚什么,我需要做的。
感谢您的帮助。
解决方案
的#include<地图和GT;
#包括LT&;串GT;
#包括LT&;&iostream的GT;
#包括LT&;升压/ any.hpp>诠释的main()
{
尝试
{
性病::地图<的std ::字符串,提振::任何>米;
M [一] = 2;
M [B] =的static_cast<字符常量*>(害群之马); INT I =提振:: any_cast< INT>(M [一]);
性病::法院LT&;< 我(<< I<<)\\ n; INT J =提振:: any_cast< INT>(M [B]); //抛出异常
性病::法院LT&;< 歼(<< J<<)\\ n;
}
抓住(...)
{
性病::法院LT&;< 异常\\ N的;
}}
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.
I've never used boost before but have looked at the fusion library but can't figure out what I need to do.
Thanks for your help.
解决方案
#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 << ")\n";
int j = boost::any_cast<int>(m["b"]); // throws exception
std::cout << "J(" << j << ")\n";
}
catch(...)
{
std::cout << "Exception\n";
}
}
这篇关于你如何让一个异构的boost ::地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文