C++ How to create a heterogeneous container

前端 未结 4 1749
攒了一身酷
攒了一身酷 2021-01-01 01:25

I need to store a series of data-points in the form of (name, value), where the value could take different types.

I am trying to use a class template for each data-

4条回答
  •  Happy的楠姐
    2021-01-01 01:32

    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 variant_type;
    
    struct Print: boost::static_visitor<>
    {
      void operator()(Foo const& f) const { f.print(std::cout); }
    
      template 
      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
    }
    

提交回复
热议问题