你如何制作异构 boost::map?

2021-12-24 00:00:00 c++ map boost

我想要一个具有同构键类型但具有异构数据类型的映射.

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
";
    }

}

相关文章