引发编译时错误
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(
相关文章:
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 如何在常量计算表达式中获取编译时错误?
- C++根据调用的构造函数强制编译时错误
- 使用 std::iterator_traits<> 时编译时错误不明确
- is_same和variadic模板编译时错误无效转换
- 私有运营商删除会触发 GCC 和 Clang 的编译时错误,但不会在 MSVC 上触发编译时错误
- 运行时与编译时多态性:更好的可读性与编译时错误检查,更重要的是
- 引发编译时错误
- 为什么调用不明确的 ctor 时没有编译时错误?
- 在 sizeof 运算符上强制编译时错误
- 未经授权的私有类成员访问会产生编译时错误而不是运行时错误?
- 从Mac上的终端编译时C 错误
- 使用MINGW-W64使用-M32选项(32位代码)编译时错误
- C++线程错误 - 带有类参数的编译时错误
- 如果编译时间构量参数是错误的,则生成编译时错误
- 尝试调用指向成员函数的函数指针时出现编译时错误
- 编译时错误:删除了联合默认构造函数
- 初始化启动对象时出现编译时错误
- 如果在C++中将成员添加到类中,则会导致编译时错误的技术
- 如何设计可序列化类以使任何非序列化属性都会导致编译时错误