当库用户为模板类的模板参数使用错误类型时,如何实现错误消息?
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");
};
你需要 sizeof(T) == 0
因为 static_assert
总是被评估,并且需要依赖于 T
否则它会始终触发,即使对于有效的 T
。
关于c++ - 为类的特征特化实现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40472706/