为 class 的特征特化实施错误消息

Implement error message for trait specialization of class

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

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