你如何制作异构 boost::map? [英] how do you make a heterogeneous boost::map?

查看:14
本文介绍了你如何制作异构 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆