C++ สมัยใหม่และวิธีเทียบเคียงใน C

C++ Lambda และ Closure แบบ C

Lambda สร้าง callable ไม่มีชื่อที่ capture state ได้ ส่วน C ส่ง context ชัดเจน

C++ Lambda และ Closure แบบ C คืออะไร?

Lambda สร้าง callable ไม่มีชื่อที่ capture state ได้ ส่วน C ส่ง context ชัดเจน

Capture context สำหรับ callback

ประเด็นสำคัญ

  • เข้าใจกลไก C ก่อน abstraction ของ C++
  • ใช้ RAII และ value semantics แสดง ownership
  • เลือก abstraction ที่ type-safe แทน macro และ cast

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>

int above(int value, void *context) {
    return value > *(int *)context;
}

int main(void) {
    int values[] = {2, 7, 4, 9};
    int threshold = 5;
    int count = 0;
    for (int index = 0; index < 4; ++index) {
        count += above(values[index], &threshold);
    }
    printf("%d\n", count);
}
ผลลัพธ์ที่คาดหวัง
2
C++
รันโค้ด →
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector values{2, 7, 4, 9};
    int threshold = 5;
    auto above = [threshold](int value) {
        return value > threshold;
    };
    std::cout << std::count_if(values.begin(), values.end(), above)
              << '\n';
}
ผลลัพธ์ที่คาดหวัง
2

เปรียบเทียบ C และ C++

ฟังก์ชัน C รับ void* แล้ว cast ส่วน C++ lambda capture threshold by value และเก็บ type information

C

C ใช้ prefix, callback, macro และ context struct

C++

ภาษาให้ abstraction ที่มี scope และ type-safe

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • เขียนกลไก C ก่อน
  • แทน manual cleanup ด้วย RAII
  • ตรวจ allocation และ virtual dispatch