Line data Source code
1 : /**
2 : * Copyright Soramitsu Co., Ltd. All Rights Reserved.
3 : * SPDX-License-Identifier: Apache-2.0
4 : */
5 :
6 : #ifndef IROHA_CLONEABLE_HPP
7 : #define IROHA_CLONEABLE_HPP
8 :
9 : #include <memory>
10 :
11 : /**
12 : * Functions and interface for creation cloneable classes with
13 : * smart pointers.
14 : *
15 : * Usage:
16 : * struct Base : object::cloneable<Base> {
17 : * // ... other methods
18 : * };
19 : *
20 : * struct Derived : Base {
21 : * // ... other methods
22 : * protected:
23 : * Derived* clone() const override {
24 : * return new Derived(*this);
25 : * }
26 : * };
27 : *
28 : * Derived derived;
29 : * auto c1 = clone(derived);
30 : */
31 :
32 : /**
33 : * Function to clone from Cloneable.
34 : * @tparam T - derived from Cloneable
35 : * @param object - object to clone
36 : * @return clone of object
37 : */
38 : template <typename T>
39 : std::unique_ptr<T> clone(const T &object) {
40 : using base_type = typename T::base_type;
41 : static_assert(std::is_base_of<base_type, T>::value,
42 : "T object has to derived from T::base_type");
43 6361 : auto ptr = static_cast<const base_type &>(object).clone();
44 6361 : return std::unique_ptr<T>(static_cast<T *>(ptr));
45 : }
46 :
47 : /**
48 : * Helper function to copy from pointer to Cloneable.
49 : * @tparam T - derived from Cloneable
50 : * @param object - object to clone
51 : * @return clone of object
52 : */
53 : template <typename T>
54 : auto clone(T *object) {
55 9 : return clone(*object);
56 : }
57 :
58 : /**
59 : * Interface for cloneable classes.
60 : * @tparam T
61 : */
62 : template <typename T>
63 : class Cloneable {
64 : public:
65 : using base_type = T;
66 :
67 : virtual ~Cloneable() = default;
68 :
69 : protected:
70 : /**
71 : * Polymorphic clone constructor.
72 : * Method guarantees deep-copy.
73 : * @return pointer to cloned object
74 : */
75 : virtual T *clone() const = 0;
76 :
77 : template <typename X>
78 : friend std::unique_ptr<X> clone(const X &);
79 : };
80 :
81 : #endif // IROHA_CLONEABLE_HPP
|