C++ How to create a heterogeneous container

此生再无相见时 提交于 2019-11-30 09:49:00

The boost library has probably what you're looking for (boost::any). You can roll your own using a wrapped pointer approach if you cannot use boost...

boost::any has already been recommended, however it's for anything, so you can't expect much from it.

If you know the various types ahead of time, you're better using boost::variant.

typedef boost::variant<Foo, Bar, Joe> variant_type;

struct Print: boost::static_visitor<>
{
  void operator()(Foo const& f) const { f.print(std::cout); }

  template <class T>
  void operator()(T const& t) const { std::cout << t << '\n'; }
};

void func(variant_type const& v) // not template
{
  boost::apply_visitor(Print(), v); // compile-time checking
                                    // that all types are handled
}

The problem with containers like this is that when you want to access something in the container, you have to determine its type and then cast it to the actual type somehow. This is ugly, inefficient and error-prone, which is why the #1 choice in C++ is to use inheritance, unless you have a very good reason not to - something I've never actually come across in my C++ career.

I was thinking that you could just have a Pair(type, void*) and write your own pop function that casts the void* depending upon the type describe in the pair and then shove these into whatever container catches your eye.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!