|
| 1 | +#ifndef _MANIF_MANIF_IMPL_CORE_UNARY_STORAGE_H_ |
| 2 | +#define _MANIF_MANIF_IMPL_CORE_UNARY_STORAGE_H_ |
| 3 | + |
| 4 | + |
| 5 | +namespace manif { |
| 6 | +namespace internal { |
| 7 | + |
| 8 | +template <typename Derived, typename RhsDerived_> |
| 9 | +struct UnaryStorage { |
| 10 | + private: |
| 11 | + // Hold a reference to leaf expressions to avoid copies, but a copy of other |
| 12 | + // expressions to avoid references to temporaries. |
| 13 | + using RhsStore = internal::storage_t<RhsDerived_>; |
| 14 | + |
| 15 | + // Helper to lazily instantiate is_constructible check in forwarding constructor |
| 16 | + // We use this inside std::conjunction. |
| 17 | + template <typename...> |
| 18 | + struct copy_not_applicable : std::true_type {}; |
| 19 | + |
| 20 | + // Case for exactly one argument: need to check whether copy constructor applies |
| 21 | + template <typename Arg> |
| 22 | + struct copy_not_applicable<Arg> |
| 23 | + : tmp::bool_constant<!std::is_same<std::decay_t<Arg>, Derived>{}> {}; |
| 24 | + |
| 25 | + public: |
| 26 | + // Forward args to rhs (version for one argument) |
| 27 | + // Disable if copy ctor would apply - https://stackoverflow.com/a/39646176 |
| 28 | + template <typename Arg, |
| 29 | + std::enable_if_t<tmp::conjunction<copy_not_applicable<Arg>, |
| 30 | + std::is_constructible<RhsStore, Arg>>{}, |
| 31 | + bool> = true> |
| 32 | + explicit UnaryStorage(Arg &&arg) : rhs_{std::forward<Arg>(arg)} {} |
| 33 | + |
| 34 | + // Forward args to rhs (version for 0 or more than 1 argument) |
| 35 | + template < |
| 36 | + typename... Args, |
| 37 | + std::enable_if_t<tmp::conjunction<copy_not_applicable<Args...>, |
| 38 | + std::is_constructible<RhsStore, Args...>>{}, |
| 39 | + bool> = true> |
| 40 | + explicit UnaryStorage(Args &&... args) : rhs_{std::forward<Args>(args)...} {} |
| 41 | + |
| 42 | + UnaryStorage() = delete; |
| 43 | + /** Copy constructor */ |
| 44 | + UnaryStorage(const UnaryStorage &) = default; |
| 45 | + /** Move constructor */ |
| 46 | + UnaryStorage(UnaryStorage &&) = default; |
| 47 | + /** Copy assignment operator */ |
| 48 | + UnaryStorage &operator=(const UnaryStorage &) = default; |
| 49 | + /** Move assignment operator */ |
| 50 | + UnaryStorage &operator=(UnaryStorage &&) = default; |
| 51 | + |
| 52 | + const RhsStore &rhs() const & { |
| 53 | + return rhs_; |
| 54 | + } |
| 55 | + |
| 56 | + RhsStore &rhs() & { |
| 57 | + return rhs_; |
| 58 | + } |
| 59 | + |
| 60 | + RhsStore rhs() && { |
| 61 | + return rhs_; |
| 62 | + } |
| 63 | + |
| 64 | + protected: |
| 65 | + RhsStore rhs_; |
| 66 | +}; |
| 67 | + |
| 68 | +} // namespace internal |
| 69 | +} // namespace manif |
| 70 | + |
| 71 | +#endif // _MANIF_MANIF_IMPL_CORE_UNARY_STORAGE_H_ |
0 commit comments