What's the best way to get the type contained by an std::optional?

Viewed 118

I'm wondering what the simplest way is of getting the type contained by an std::optional. The solution I thought of is:

#include <type_traits>
template <typename Optional_T>
    struct GetOptionalContainedType
    {
        using type = std::remove_reference<decltype(Optional_T::value())>::type;
    };

This requires the inclusion of the <type_traits> header, (I need std::remove_reference) for this method because ::value() returns a reference to the type, right?

1 Answers

No extra headers are required, just <optional>, which you already must include.

#include <optional>

template <typename Optional_T> struct GetOptionalContainedType;

template<typename T>
struct GetOptionalContainedType<std::optional<T>>
    {
        using type = T;
    };
Related