dot*_*dot 1 c++ templates specialization sfinae template-specialization
当库用户对模板类的模板参数使用错误类型时,如何实现错误消息?
\n\ntest.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}\nRun Code Online (Sandbox Code Playgroud)\n\n该代码未按预期编译。但我不能让编译器仅在用户使用错误的类型时才显示错误。
\n\n错误信息为g++ test.cpp
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;\nRun Code Online (Sandbox Code Playgroud)\n\n问题:它没有打印我想要的错误消息 ( Sorry, foo<T> for non-integral type T has not been implemented.)
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)
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.