aboutsummaryrefslogtreecommitdiff
path: root/libs/plugin_python/src/pybind11-utils/include/pybind11_utils/smart_variant.h
blob: bd7bd9b52c8f4f4739680a00a33640f643bfc09a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#ifndef PYTHON_PYBIND11_UTILS_SMART_VARIANT_H
#define PYTHON_PYBIND11_UTILS_SMART_VARIANT_H

#include <variant>

namespace mo2::python {

    namespace detail {

        // simple template class that should be specialized to expose proper fromXXX
        // methods
        //
        template <class T>
        struct smart_variant_converter {
            template <class U>
            static T from(U&& u)
            {
                return T{std::forward<U>(u)};
            }
        };

    }  // namespace detail

    // a smart_variant is a std::variant that can be automatically converted to any of
    // its type via custom operator T()
    //
    // user should specialize detail::smart_variant_converter to provide proper
    // conversions
    //
    template <class... Args>
    struct smart_variant : std::variant<Args...> {
        using std::variant<Args...>::variant;

        template <class T, std::enable_if_t<
                               std::disjunction_v<std::is_same<T, Args>...>, int> = 0>
        operator T() const
        {
            return std::visit(
                [](auto const& t) -> T {
                    if constexpr (std::is_same_v<std::decay_t<decltype(t)>, T>) {
                        return t;
                    }
                    else {
                        return detail::smart_variant_converter<T>::from(t);
                    }
                },
                *this);
        }
    };

}  // namespace mo2::python

#endif