Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Static Assert ใน C++

static_assert เป็นฟังก์ชันที่มีประโยชน์สำหรับโปรแกรมเมอร์ในการพิมพ์ข้อผิดพลาดบนหน้าจอหลังจากคอมไพล์โปรแกรมโดยไม่ทำให้เอาต์พุทซับซ้อนเกินไป

ใน C++11 และ C++14 static_assert มีฟังก์ชันการทำงานที่แตกต่างกัน ซึ่งหมายความว่าเราต้องเขียนข้อความของตัวเองขณะกำหนด static_assert อย่างไรก็ตาม ใน C++17 static_assert สามารถเรียกใช้ได้โดยไม่ต้องส่งผ่านข้อความ

มันเข้ากันได้กับฟังก์ชันของไลบรารี asserts อื่นๆ เช่น BOOST_STATIC_ASSERT ด้วย

ไวยากรณ์

static_assert(condition, message);

ใน C++17 สามารถใช้ได้โดยไม่ต้องมี message:

static_assert(condition);

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

template <typename T, size_t N, typename F>
void fillArray(array<T, N> &a, F &&f) {
    static_assert(is_convertible<typename result_of<F()>::type, T>::value, 
                  "Incompatible type returned by fun()");
    for (auto &x : a)
        x = f();
}

int main() {
    array<vector<string>, 20> a;
    fillArray(a, []() { return vector<string>{"TutorialsPoint"}; });
    return 0;
}

ผลลัพธ์

error: static assertion failed: Incompatible type returned by fun()

static_assert ช่วยให้จับข้อผิดพลาดได้ในขั้นตอนคอมไพล์ (Compile-time) แทนที่จะเป็นขณะรันโปรแกรม (Runtime) ทำให้โค้ดปลอดภัยและเชื่อถือได้มากขึ้น