Advertisement
Guest User

creator

a guest
Dec 6th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. template<class T>
  2. class Creator
  3. {
  4. public:
  5.     ~Creator() = default;
  6.  
  7.     //Constructs from parameter pack and forwards them to object's constructor
  8.     template<
  9.         class ... ArgsT,
  10.         class = typename std::enable_if<!std::is_abstract<T>::value>::type>   //only defined when T is not abstract
  11.         explicit Creator(ArgsT&& ... args)
  12.         : functor([args ...]  /*copy*/
  13.     {
  14.         return std::make_unique<T>(args ...);
  15.     })
  16.     {}
  17.  
  18.     //move ctor
  19.     template<
  20.         class OtherT,
  21.         class = typename std::enable_if<std::is_base_of<T, OtherT>::value>::type>
  22.         Creator(Creator<OtherT>&& other)
  23.         : functor(std::move(other.functor))
  24.     {}
  25.  
  26.     //copy ctor
  27.     template<
  28.         class OtherT,
  29.         class = typename std::enable_if<std::is_base_of<T, OtherT>::value>::type>
  30.         Creator(const Creator<OtherT>& other)
  31.         : functor(other.functor)
  32.     {}
  33.  
  34.     //move assign
  35.     template<
  36.         class OtherT,
  37.         class = typename std::enable_if<std::is_base_of<T, OtherT>::value>::type>
  38.         Creator<T>& operator=(Creator<OtherT>&& other)
  39.     {
  40.         functor = std::move(other.functor);
  41.         return *this;
  42.     }
  43.  
  44.     //copy assign
  45.     template<
  46.         class OtherT,
  47.         class = typename std::enable_if<std::is_base_of<T, OtherT>::value>::type>
  48.         Creator<T>& operator=(const Creator<OtherT>& other)
  49.     {
  50.         functor = other.functor;
  51.         return *this;
  52.     }
  53.  
  54.     inline auto operator()()
  55.     {
  56.         return functor();
  57.     }
  58. private:
  59.     std::function<std::unique_ptr<T>()> functor;
  60.  
  61.     template<class OtherT> friend class Creator;
  62. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement