Allium  0.1.0
cloneable.hpp
1 // Copyright 2020 Hannah Rittich
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 ALLIUM_UTIL_CLONEABLE_HPP
16 #define ALLIUM_UTIL_CLONEABLE_HPP
17 
18 #include <memory>
19 #include <sstream>
20 #include <allium/util/assert.hpp>
21 
22 namespace allium {
23 
30 class Cloneable {
31  public:
32  virtual ~Cloneable();
33 
34  private:
35  virtual Cloneable* clone() const& = 0;
36 
37  template <typename T>
38  std::enable_if_t<std::is_base_of<Cloneable, T>::value,
39  std::unique_ptr<T>>
40  friend clone(const T& o);
41 };
42 
43 template <typename T>
44 std::enable_if_t<std::is_base_of<Cloneable, T>::value,
45  std::unique_ptr<T>>
46 clone(const T& o)
47 {
48  Cloneable* ptr = static_cast<const Cloneable&>(o).clone();
49 
50  allium_assert(
51  dynamic_cast<T*>(ptr) != nullptr,
52  std::string("The clone method is not overridden in ")
53  + typeid(*ptr).name()
54  + ".");
55 
56  return std::unique_ptr<T>(static_cast<T*>(ptr));
57 }
58 
59 }
60 
61 #endif
A class that allows cloning of objects.
Definition: cloneable.hpp:30