我最近开始学习现代模板元编程,并为自己编写了一个类型的 index_of 函数。
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>;
};
问题是我最后一个专业
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
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");
};
但这每次都会抛出一个编译错误,即使它不匹配也是如此。
如果此模板特化匹配,我想抛出带有自定义错误消息的编译错误。我该怎么做?
最佳答案
如果您将 static_assert(false,...)
放入模板特化中,则始终无法从中生成有效代码。这是格式错误的,不需要诊断。
解决此问题的方法是让您的 static_assert
依赖于模板参数:
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");
}
关于c++ - 在模板特化中强制编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413960/