Line data Source code
1 : #pragma once 2 : 3 : #include <memory> 4 : 5 : namespace elsa 6 : { 7 : /** 8 : * @brief Class implementing polymorphic clones with smart pointers and CRTP, as well as 9 : * comparison operators. 10 : * 11 : * @author Tobias Lasser 12 : * 13 : * This class provides a clone method using CRTP to support covariance with smart pointers. 14 : * For details see 15 : * https://www.fluentcpp.com/2017/09/12/how-to-return-a-smart-pointer-and-use-covariance/. 16 : */ 17 : template <typename Derived> 18 : class Cloneable 19 : { 20 : public: 21 : /// default constructor 22 287255 : Cloneable() = default; 23 : /// virtual default destructor 24 364213 : virtual ~Cloneable() = default; 25 : 26 : /// clone object, returning an owning unique_ptr 27 260110 : std::unique_ptr<Derived> clone() const { return std::unique_ptr<Derived>(cloneImpl()); } 28 : 29 : /// comparison operators 30 16599 : bool operator==(const Derived& other) const { return isEqual(other); } 31 : 32 14375 : bool operator!=(const Derived& other) const { return !(*this == other); } 33 : 34 : /// delete implicitly declared copy assignment to prevent copy assignment of derived classes 35 : Cloneable& operator=(const Cloneable&) = delete; 36 : 37 : protected: 38 : /// actual clone implementation method, abstract to force override in derived classes 39 : virtual Derived* cloneImpl() const = 0; 40 : 41 : /// actual comparison method, abstract to force override in derived classes 42 : virtual bool isEqual(const Derived& other) const = 0; 43 : 44 : /// default copy constructor, protected to not be publicly available (but available for 45 : /// cloneImpl() 46 74042 : Cloneable(const Cloneable&) = default; 47 : }; 48 : 49 : } // namespace elsa