为类的特征专业化实现错误消息

时间:2016-11-07 19:07:43

标签: 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.

1 个答案:

答案 0 :(得分:4)

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也是如此。