Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace detail {
- /// Helper template that is forwarded to the mixins used
- /// for the extension of wrapper<•> in order to enable
- /// access to the actual type `Derived`
- template <typename Derived>
- struct Cast {
- using type = Derived;
- template <typename T>
- static constexpr Derived& self(T* self) { return *static_cast<Derived*>(self); }
- template <typename T>
- static constexpr Derived const& self(T const* self) { return *static_cast<Derived const*>(self); }
- };
- /// This helper template is used to derive from all the Mixins
- /// one after another, making sure the constructor is mixed in as well:
- template <typename Cast, typename T,template <typename...> class...Mixins>
- struct wrapper_impl;
- template <typename Cast, typename T,template <typename...> class First, template <typename...> class...Rest>
- struct wrapper_impl<Cast, T, First, Rest...>
- : First<Cast, T>
- , wrapper_impl<Cast, T, Rest...>
- {
- using First<Cast, T>::First;
- using wrapper_impl<Cast, T, Rest...>::wrapper_impl;
- };
- template <typename Cast, typename T, template <typename...> class First>
- struct wrapper_impl<Cast, T, First>
- : First<Cast, T>
- , wrapper_impl<Cast, T>
- {
- using First<Cast, T>::First;
- using wrapper_impl<Cast, T>::wrapper_impl;
- };
- template <typename Cast, typename T>
- struct wrapper_impl<Cast, T> {
- };
- }
- template <typename T, typename Tag, template <typename...> class...Mixins>
- class wrapper : public detail::wrapper_impl<detail::Cast<wrapper<T,Tag,Mixins...>>, T, Mixins...> {
- public:
- using value_type = T;
- using detail::wrapper_impl<detail::Cast<wrapper<T,Tag,Mixins...>>, T, Mixins...>::wrapper_impl;
- T& get() { return *reinterpret_cast<T*>(&m_buffer); }
- T const& get() const { return *reinterpret_cast<T const*>(&m_buffer); }
- template <typename...Args>
- void construct(Args&&...args) {
- new (&m_buffer) T(std::forward<Args>(args)...);
- }
- void destruct() {
- get().~T();
- }
- ~wrapper() {
- destruct();
- }
- private:
- std::aligned_storage_t<sizeof(T), alignof(T)> m_buffer;;
- };
- template <typename T>
- struct constructor_from {
- template <typename Cast, typename U>
- struct mixin {
- explicit mixin(T const& value) {
- Cast::self(this).construct(U{value});
- }
- };
- };
- using my_int = wrapper<int, struct Tag, constructor_from<int>::mixin>;
- my_int instance{42};
- using my_int = wrapper<int, struct Tag, constructor_from<int>::mixin>;
- my_int instance{4.2};
Add Comment
Please, Sign In to add comment