boost::hana how to check if a type is std::optional?

Viewed 1528

I searched the boost::hana::traits I cannot find anything related to checking concept of types. For example is_vector, is_optional. Is there any tools in hana can simplify this? Moreover, I would like to branch the code based on the result thus it needs to be used in hana::eval_if. Can anyone show me some examples?

I would like follow to work:

hana::eval_if(
    is_vector(hana::decltype_(val)),
    [&](auto _) {std::cout << "is vector\n";},
    [&](auto _) {
        hana::eval_if(
                is_optional(hana::decltype_(val)),
                [&](auto _) { std::cout << "is optional\n"; },
                [&](auto _) { std::cout << "neither vector nor optional\n"; }
        );
    }
);
3 Answers

You just sfinae that.

E.g.:

template <typename T, typename Enable = void>
struct is_optional : std::false_type {};

template <typename T>
struct is_optional<std::optional<T> > : std::true_type {};

template <typename T>
struct is_optional<boost::optional<T> > : std::true_type {};

Alternatively, you can use constexpr functions for easier use with actual variables:

Live On Coliru

#include <string>
#include <iostream>
#include <optional>
#include <boost/optional.hpp>
#include <boost/hana.hpp>
namespace hana = boost::hana;

namespace {
    template <typename T>
        constexpr bool is_optional(T const&) { return false; }
    template <typename T>
        constexpr bool is_optional(std::optional<T> const&) { return true; }
    template <typename T>
        constexpr bool is_optional(boost::optional<T> const&) { return true; }
}

template <typename T>
auto deref_opt(T const& v) {
    if constexpr(is_optional(v))
        return *v;
    else
        return v;
}

int main() {
    std::optional<double> od = 3.14;
    boost::optional<std::string> os = std::string("Pi");
    int i = 314;

#define DEMO(x) std::cout << #x << ": " << std::boolalpha << is_optional(x) << " " << deref_opt(x) << "\n";
    DEMO(i);
    DEMO(os);
    DEMO(od);
}

Prints

i: false 314
os: true Pi
od: true 3.14

Now with concepts in c++20, the following is possible:

#include <concepts>
#include <optional>

template <typename T>
concept any_optional = std::same_as<T, std::optional<typename T::value_type>>;

C++20 way of doing this:

template< typename T >
concept Optional = requires( T t )
{
    typename T::value_type;
    std::same_as< T, std::optional< typename T::value_type > >;
};
Related