All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Pages
Cloneable.h
Go to the documentation of this file.
1 // Copyright 2015 Thomas Trapp
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef HEXT_CLONEABLE_H_INCLUDED
16 #define HEXT_CLONEABLE_H_INCLUDED
17 
18 /// @file
19 /// Defines template hext::Cloneable
20 
21 #include <memory>
22 #include <type_traits>
23 
24 
25 namespace hext {
26 
27 
28 /// Curiously recurring template pattern that extends a base class to provide
29 /// a virtual method Cloneable::clone().
30 ///
31 /// @tparam Derived: A subclass of Cloneable that is copy constructible.
32 /// @tparam Base: The base class that shall be extended.
33 template<typename Derived, typename Base>
34 class Cloneable : public Base
35 {
36 public:
37  /// Clones objects of template type Derived and returns an owning pointer to
38  /// the newly allocated Base.
39  ///
40  /// Fails at compile time if template parameter Base is not a base of template
41  /// parameter Derived or if template parameter Derived is not copy
42  /// constructible.
43  virtual std::unique_ptr<Base> clone() const
44  {
45  static_assert(std::is_base_of<Base, Derived>::value,
46  "template argument <Base> is not a base of "
47  "template argument <Derived>");
48  static_assert(std::is_copy_constructible<Derived>::value,
49  "template argument <Derived> is not copy constructible");
50  // This static_cast is safe because we have just asserted that Derived is a
51  // subclass of Base.
52  return std::make_unique<Derived>(static_cast<const Derived&>(*this));
53  }
54 };
55 
56 
57 } // namespace hext
58 
59 
60 #endif // HEXT_CLONEABLE_H_INCLUDED
61 
virtual std::unique_ptr< Base > clone() const
Clones objects of template type Derived and returns an owning pointer to the newly allocated Base...
Definition: Cloneable.h:43
Curiously recurring template pattern that extends a base class to provide a virtual method Cloneable:...
Definition: Cloneable.h:34