温馨提示×

c++ static_assert常见错误示例

c++
小樊
81
2024-11-25 05:42:33
栏目: 编程语言

static_assert 是 C++11 引入的一个关键字,用于在编译时进行断言检查

  1. 未定义的常量:
#include <iostream>
#include <type_traits>

int main() {
    static_assert(true, "This should not cause a compilation error");
    static_assert(false, "This will cause a compilation error"); // Error: constant expression required
}
  1. 类型不匹配:
#include <iostream>
#include <type_traits>

template <typename T>
void foo(T t) {
    static_assert(std::is_same<T, int>::value, "T must be an integer");
}

int main() {
    foo(42); // OK
    foo(3.14); // Error: static assertion failed: T must be an integer
}
  1. 表达式计算失败:
#include <iostream>

int main() {
    int a = 10;
    int b = 0;
    static_assert(a / b == 5, "Division by zero should not occur"); // Error: static assertion failed: a / b == 5
}
  1. 自定义类型特性检查失败:
#include <iostream>
#include <type_traits>

struct MyStruct {
    int x;
};

template <typename T>
void foo(T t) {
    static_assert(std::is_integral<T>::value, "T must be an integral type");
}

int main() {
    foo(MyStruct{42}); // OK
    foo(3.14); // Error: static assertion failed: T must be an integral type
}

这些示例展示了 static_assert 在不同情况下的常见错误。注意,当 static_assert 失败时,编译器会生成一个编译错误,并显示提供的错误消息。

0