可以将不同类型的对象放在一个数组中吗?

时间:2012-11-06 08:46:15

标签: c++

这是事情,我有几个std::map,像这样:

std::map<int, std::set> map_1;
std::map<int, std::string> map_2;
std::map<int, long> map_3;
...

还有几个数字,每个数字都与上面列出的一张地图有关,比如

1 -> map_2
2 -> map_1
3 -> map_3
...

我要做的是,将所有地图放入一个数组中,然后访问每个数字的地图 就像访问该数组的元素一样,如下所示:

arr = [map_2, map_1, map_3];
// let x be a number
map_x = arr[x];
do_something(map_x)

这样,我可以自己写switch...case,对吗?

但我可以把它们放在一起吗?

2 个答案:

答案 0 :(得分:1)

这样做的正确方法是上课。为特定类型的映射创建基类map和模板化子类。然后,您可以创建一个map*元素数组。

答案 1 :(得分:0)

另一种解决方案是使用boost::variant

将所有地图类型放入变体(boost::variant<std::map<int, std::set>, std::map<int, std::string>, std::map<int, long>>),然后像(do_something那样写访问者应该已经超载了,对吧?):

class do_something_visitor
    : public boost::static_visitor<>
{
public:
    template <typename T>
    void operator()(T &map) const
    {
        do_something(map);
    }
};

然后对您的变体数组中的项目应用访问(boost::apply_visitor)。