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

编程入门 行业动态 更新时间:2024-10-10 19:20:42
本文介绍了你如何制作异构 boost::map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 09:01:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/826358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异构   boost   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!