Union in c++ are they feasible

前端 未结 5 1808
死守一世寂寞
死守一世寂寞 2021-02-07 01:45

Can a union in C++ have a member function? How do union with data members and member functions exist if an object is created?

If I suppose yes, then are they feasible an

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-07 02:23

    The union is a C-structure, and does not work well with C++ types (there are a number of caveats actually). However there already exist a C++ equivalent, which effectively work with all C++ classes and user-defined classes and is even safer than the union!

    Behold Boost.Variant!

    You can define a boost::variant and it'll make sure:

    • that the appropriate constructor/destructor/assignment operator is run, when required
    • that you only access the lastest value that was set

    And it even comes with the excellent: boost::static_visitor which let's you apply a method on the union regardless of its type and provide compile-time checking to warn you whenever you have forgotten one of the possible types!

    class MyVisitor: boost::static_visitor
    {
    public:
      int operator()(std::string const& s) const {
        return boost::lexical_cast(s);
      }
    
      int operator()(Foo const& f) const { return f.getAsInt(); }
    
      int operator()(char c) const { return c; }
    };
    
    typedef boost::variant MyVariant;
    
    int main(int argc, char* argv[]) {
      MyVariant v; // the std::string is constructed
    
      if (argc % 2) { v = Foo(4); }
      if (argc % 3) { v = argv[1][0]; }
      if (argc % 5) { v = argv[1]; }
    
      std::cout << boost::apply_visitor(MyVisitor(), v) << '\n';
      return 0;
    }
    

    Also... it's as efficient (fast) as a union, and does not involve any dynamic look-up like Boost.Any would.

提交回复
热议问题