c++ - 在模板特化中强制编译时错误

标签 c++ templates c++11 template-meta-programming

我最近开始学习现代模板元编程,并为自己编写了一个类型的 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/

相关文章:

c++ - atof 随机无法正常工作

c++ - 为什么不能指向指针,在没有强制转换的情况下访问结构成员?

c++ - 复制构造函数指针对象

c++ - 将 Protobuf 转换为具有类似功能的 ROS 消息

c++ - 构造函数中模板化类成员的继承

c++ - 特定成员函数的部分特化

c++ - 根据模板参数选择合适的复制构造函数

c++ - 创建恒定大小 vector 的恒定大小 vector

c++ - 只有 operator() 的结构和普通函数之间的实际区别

c++ - 如何在不重复的情况下随机迭代 vector 的每个元素