Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i assert, compile time, that the nth element of a tuple is an optional of some type?

Tags:

c++

I need to check if the nth element of a tuple is an optional of some type. It has to be an std::optional and not a std::variant (which could have made the code simpler).

My first instinct is the following. But this throws a compiler error.

template<int N, typename TupleToCheck>
void StaticCheck() {
    using NthType = typename tuple_element<N, TupleToCheck>::type;
    static_assert(std::is_same<NthType, std::optional<NthType::value_type>>);
}

I suspect that this is because the compiler does not know if NthType could have a type value_type defined within it. Is there a way to achieve this?

like image 756
Sway Avatar asked Sep 23 '20 20:09

Sway


1 Answers

You did not post the error, but this scheme should work for all templates regardless whether ::value_type exists:

#include <tuple>
#include <optional>


template<typename T>
struct is_optional{
    constexpr static bool value = false;
};

template<typename T>
struct is_optional<std::optional<T>>{
    constexpr static bool value = true;
};

template<typename T>
constexpr bool is_optional_v = is_optional<T>::value;

template<int N, typename TupleToCheck>
void StaticCheck() {
    static_assert(is_optional_v<std::tuple_element_t<N,TupleToCheck>>);
}


int main(){

    using t1 = std::tuple<int,std::optional<double>,double>;

    StaticCheck<1,t1>();
}
like image 57
Quimby Avatar answered Sep 30 '22 08:09

Quimby