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
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.