如果库用户对模板类的模板参数使用了错误的类型,如何实现错误消息?
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.
)
答案 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");
};
您需要sizeof(T) == 0
,因为始终会评估static_assert
,并且需要依赖T
,否则它将始终触发,即使对于有效的T
也是如此。