hnOsmium0001

(copied) polymorphic clone helper

Mar 21st, 2020
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. // Polymorphic clone utilities
  2. namespace HOEngine {
  3.     template <typename T>
  4.     class AbstractFunc;
  5.  
  6.     template <typename T>
  7.     class VirtualInheritFrom : public virtual T {
  8.         using T::T;
  9.     };
  10.  
  11.     template <typename Derived, typename... Bases>
  12.     class CloneInherit : public Bases... {
  13.     public:
  14.         virtual ~CloneInherit() = default;
  15.  
  16.         std::unique_ptr<Derived> Clone() const {
  17.             return std::unique_ptr<Derived>(static_cast<Derived*>(this->CloneImpl()));
  18.         }
  19.  
  20.     private:
  21.         virtual Derived* CloneImpl() const override {
  22.             return new Derived(static_cast<const Derived&>(*this));
  23.         }
  24.     };
  25.  
  26.     template <typename Derived, typename... Bases>
  27.     class CloneInherit<AbstractFunc<Derived>, Bases...> : public Bases... {
  28.     public:
  29.         virtual ~CloneInherit() = default;
  30.  
  31.         std::unique_ptr<Derived> Clone() const {
  32.             return std::unique_ptr<Derived>(static_cast<Derived*>(this->CloneImpl()));
  33.         }
  34.  
  35.     private:
  36.         virtual Derived* CloneImpl() const = 0;
  37.     };
  38.  
  39.     template <typename Derived>
  40.     class CloneInherit<Derived> {
  41.     public:
  42.         virtual ~CloneInherit() = default;
  43.  
  44.         std::unique_ptr<Derived> Clone() const {
  45.             return std::unique_ptr<Derived>(static_cast<Derived*>(this->CloneImpl()));
  46.         }
  47.  
  48.     private:
  49.         virtual Derived* CloneImpl() const override {
  50.             return new Derived(static_cast<const Derived&>(*this));
  51.         }
  52.     };
  53.  
  54.     template <typename Derived>
  55.     class CloneInherit<AbstractFunc<Derived>> {
  56.     public:
  57.         virtual ~CloneInherit() = default;
  58.  
  59.         std::unique_ptr<Derived> Clone() const {
  60.             return std::unique_ptr<Derived>(static_cast<Derived*>(this->CloneImpl()));
  61.         }
  62.  
  63.     private:
  64.         virtual Derived* CloneImpl() const = 0;
  65.     };
  66. }
Advertisement
Add Comment
Please, Sign In to add comment