Skip to content

Instantly share code, notes, and snippets.

@mpusz
Created December 14, 2012 11:36
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 mpusz/4284800 to your computer and use it in GitHub Desktop.
Save mpusz/4284800 to your computer and use it in GitHub Desktop.
[OOD] Prototype design pattern with CRTP usage
//
// author: Mateusz Pusz
//
#include <memory>
template<typename T, typename ...Args>
inline std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
}
class CProtectedCopyable {
protected:
CProtectedCopyable(const CProtectedCopyable&) = default;
public:
CProtectedCopyable() = default;
};
class CProduct : CProtectedCopyable {
public:
virtual ~CProduct() {}
virtual std::unique_ptr<CProduct> Clone() const = 0;
};
template<typename T>
class CProductCRTP : public CProduct {
public:
virtual std::unique_ptr<CProduct> Clone() const { return make_unique<T>(static_cast<const T&>(*this)); }
};
// ----------------- HUGE CLASS HIERARCHY -------------------
class CProductWheelLoader : public CProductCRTP<CProductWheelLoader> {};
class CProductBulldozer : public CProductCRTP<CProductBulldozer> {};
class CProductBackhoe : public CProductCRTP<CProductBackhoe> {};
// .....................................
int main()
{
CProductWheelLoader loader;
CProduct &product = loader;
auto copy = product.Clone();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment