Created
December 14, 2012 11:36
-
-
Save mpusz/4284800 to your computer and use it in GitHub Desktop.
[OOD] Prototype design pattern with CRTP usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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