Is it possible to change a C++ object's class after instantiation?

后端 未结 16 2153
忘掉有多难
忘掉有多难 2021-02-02 06:50

I have a bunch of classes which all inherit the same attributes from a common base class. The base class implements some virtual functions that work in general cases, whilst eac

16条回答
  •  青春惊慌失措
    2021-02-02 07:19

    I would consider regularizing your type.

    class Base {
    public:
      virtual void whoami() { std::cout << "Base\n"; }
      std::unique_ptr clone() const {
        return std::make_unique(*this);
      }
      virtual ~Base() {}
    };
    class Derived: public Base {
      virtual void whoami() overload {
        std::cout << "Derived\n";
      };
      std::unique_ptr clone() const override {
        return std::make_unique(*this);
      }
    public:
      ~Derived() {}
    };
    struct Base_Value {
    private:
      std::unique_ptr pImpl;
    public:
      void whoami () {
        pImpl->whoami();
      }
      template
      void emplace( Args&&...args ) {
        pImpl = std::make_unique(std::forward(args)...);
      }
      Base_Value()=default;
      Base_Value(Base_Value&&)=default;
      Base_Value& operator=(Base_Value&&)=default;
      Base_Value(Base_Value const&o) {
        if (o.pImpl) pImpl = o.pImpl->clone();
      }
      Base_Value& operator=(Base_Value&& o) {
        auto tmp = std::move(o);
        swap( pImpl, tmp.pImpl );
        return *this;
      }
    };
    

    Now a Base_Value is semantically a value-type that behaves polymorphically.

    Base_Value object;
    object.emplace();
    object.whoami();
    
    object.emplace();
    object.whoami();
    

    You could wrap a Base_Value instance in a smart pointer, but I wouldn't bother.

提交回复
热议问题