Skip to content

Instantly share code, notes, and snippets.

@dacap
Created September 25, 2019 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacap/e5754d234cbe19bf87b2ffd884649a69 to your computer and use it in GitHub Desktop.
Save dacap/e5754d234cbe19bf87b2ffd884649a69 to your computer and use it in GitHub Desktop.
Impl of clonable pattern https://godbolt.org/z/ZI0py6
#include <memory>
using namespace std;
// --- library ---
template<class T>
class clonable {
public:
using Base = T;
virtual shared_ptr<T> clone() const {
return make_shared<T>(*static_cast<const T*>(this));
}
};
template<class Super, class T>
class subclonable : public Super {
public:
using Base = typename Super::Base;
shared_ptr<Base> clone() const override {
return make_shared<T>(*static_cast<const T*>(this));
}
};
// --- usage ---
class B : public clonable<B> { };
class C : public subclonable<B, C> { };
class D : public subclonable<C, D> { };
class E : public subclonable<D, E> { };
int main() {
shared_ptr<B> c = make_shared<C>();
shared_ptr<B> d = make_shared<D>();
shared_ptr<B> e = make_shared<E>();
shared_ptr<B> c2 = c->clone();
shared_ptr<B> d2 = d->clone();
shared_ptr<B> e2 = e->clone();
printf("c2=%s\n", typeid(*c2).name());
printf("d2=%s\n", typeid(*d2).name());
printf("e2=%s\n", typeid(*e2).name());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment