c++ - 为类的特征特化实现错误消息

标签 c++ templates template-specialization sfinae specialization

当库用户为模板类的模板参数使用错误类型时,如何实现错误消息?

test.cpp(改编自here)

#include <type_traits>
template <typename T, typename Enable = void>
class foo; // Sorry, foo<T> for non-integral type T has not been implemented.

template <typename T>
class foo<T, typename std::enable_if<std::is_integral<T>::value>::type>
{ };

int main()
{
    foo<float> x;
}

代码没有像预期的那样编译。但是我不能让编译器只在用户使用了错误的类型时才显示错误。

g++ test.cpp的错误信息

test.cpp: In function ‘int main()’:
test.cpp:11:13: error: aggregate ‘foo<float> x’ has incomplete type and cannot be defined
  foo<float> x;

问题:它没有打印出我想要的错误信息 (Sorry, foo<T> for non-integral type T has not been implemented.)

最佳答案

static_assert会成功的:

template <typename T, typename Enable = void>
class foo
{
    static_assert(sizeof(T) == 0, "Sorry, foo<T> for non-integral type T has not been implemented");
};

Demo

你需要 sizeof(T) == 0 因为 static_assert 总是被评估,并且需要依赖于 T 否则它会始终触发,即使对于有效的 T

关于c++ - 为类的特征特化实现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40472706/

相关文章:

c++ - 可以在 Haskell 中模拟 'correspond' 类型的 C++ 结构模式(模板特化)吗?

c++ - 模板类模板方法特化

c++ - ABC 虚拟 OStream 插入运算符

c++ - Boost spirit不动点作为整数解析器

继承语句中的 C++ 部分特化?

c++ - 如何使用 C++ 编写 vector vector 的通用打印

c++ - 在 Windows 上编译 NodeJS C++ 模块?

c++ - 以位为单位加一列是什么意思?

html - 如何在 Vaadin 中使用 HTML 模板?

c++ - 使用变量实例化模板函数