引发编译时错误

Raising compile-time errors

本文关键字:编译时错误      更新时间:2023-10-16

有没有办法在尝试函数模板的某种特化时引发编译时错误?

template<typename T> T Factorial(T n) { ... }
short n;
cout << Factorial(n); // Error, short is too small

有没有办法为模板化类的特定方法达到相同的效果?

template<typename T> class Arithmetic
{
T n;
T GCD(T m) { ... }
T Factorial() { ... }
};
Arithmetic<short> A;
short m;
cout << A.GCD(m); // Ok
cout << A.Factorial(); // Error, short is too small

这可以解决问题:

template<typename T>
class Foo {
public:
Foo() {
static_assert(sizeof(T) > sizeof(short));
}
};
int main() {
Foo<short> foo;
return 0;
}

(请注意,没有诊断消息的static_assert需要C++17(