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?
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>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With