在模板专门化中强制发生编译时错误 [英] Force a compile time error in a template specialization
问题描述
我最近开始学习现代模板元编程,并为自己编写了类型的index_of函数。
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
};
我试图像这样使用static_assert
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?
推荐答案
如果您放入 static_assert(false,...)
在模板特化中,则始终不可能从中生成有效代码。这是格式错误,不需要诊断。
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.
一种解决方法是使您的 static_assert
取决于模板参数:
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");
}
这篇关于在模板专门化中强制发生编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!