Union in c++ are they feasible

前端 未结 5 1801
死守一世寂寞
死守一世寂寞 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:17

    You can also make a template union :

    template 
    union Foo {
    public:
      Foo() {}
      Foo(const T& value) : _val(value) {}
    
      const char* data() const {
        return _tab;
      }
    
      std::size_t size() const {
        return sizeof(T);
      }
    
      char operator[](unsigned int index) const {
          return _tab[index];
      }
    
    private:
      T _val;
      char _tab[sizeof(T)];
    }
    

提交回复
热议问题