实现类的特征特化的错误消息

dot*_*dot 1 c++ templates specialization sfinae template-specialization

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

\n\n

test.cpp(从这里改编)

\n\n
#include <type_traits>\ntemplate <typename T, typename Enable = void>\nclass foo; // Sorry, foo<T> for non-integral type T has not been implemented.\n\ntemplate <typename T>\nclass foo<T, typename std::enable_if<std::is_integral<T>::value>::type>\n{ };\n\nint main()\n{\n    foo<float> x;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

该代码未按预期编译。但我不能让编译器仅在用户使用错误的类型时才显示错误。

\n\n

错误信息为g++ test.cpp

\n\n
test.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\ntest.cpp:11:13: error: aggregate \xe2\x80\x98foo<float> x\xe2\x80\x99 has incomplete type and cannot be defined\n  foo<float> x;\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n

And*_*dyG 5

static_assert will do the trick:

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");
};
Run Code Online (Sandbox Code Playgroud)

Demo

You need the sizeof(T) == 0 because the static_assert is always evaluated, and needs to depend on T otherwise it will always trigger, even for valid T.