I recently started to learn modern template metaprogramming and I wrote myself an index_of function for types.
template<std::size_t Index, class C, class A> struct mp_index_of_impl{};
template<std::size_t Index, class C,template<class...> class A,class ...Ts>
struct mp_index_of_impl<Index,C,A<C,Ts...>>{
using type = std::integral_constant<std::size_t,Index>;
};
template<std::size_t Index, class C,template<class...> class A,class ...Ts,class T1>
struct mp_index_of_impl<Index,C,A<T1,Ts...>>{
using type = typename mp_index_of_impl<Index + 1,C,A<Ts...>>::type;
};
template<std::size_t Index, class C,template<class...> class A> struct mp_index_of_impl<Index,C,A<>>{
//static_assert(false,"Does not contain type");
using type = std::integral_constant<std::size_t,0>;
};
The problem is my last specialization
template<std::size_t Index, class C,template<class...> class A>
struct mp_index_of_impl<Index,C,A<>>{
//throw a compile error here
};
I tried to use static_assert like this
template<std::size_t Index, class C,template<class...> class A> struct mp_index_of_impl<Index,C,A<>>{
static_assert(false,"Does not contain type");
};
But this will throw a compile error every time, even if it is not matched.
I want to throw a compile error with a custom error message if this template specialization is matched. How would I do this?
If you put a static_assert(false,...)
in a template specialization then it is always impossible to generate valid code from it. This is ill-formed, no diagnostic required.
A workaround to this is to make your static_assert
depend on the template parameter:
template<typename T>
struct assert_false : std::false_type
{ };
template <typename T>
inline T getValue(AnObject&)
{
static_assert( assert_false<T>::value , "Does not contain type");
}
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