Template และเทคนิค Generic ใน C
Template สร้าง implementation ที่ type-safe ส่วน C ใช้ macro, void* หรือ C11 _Generic
Template และเทคนิค Generic ใน C คืออะไร?
Template สร้าง implementation ที่ type-safe ส่วน C ใช้ macro, void* หรือ C11 _Generic
เขียน compile-time code ที่ไม่ผูก type
ประเด็นสำคัญ
- เข้าใจกลไก C ก่อน abstraction ของ C++
- ใช้ RAII และ value semantics แสดง ownership
- เลือก abstraction ที่ type-safe แทน macro และ cast
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int max_int(int left, int right) {
return left > right ? left : right;
}
double max_double(double left, double right) {
return left > right ? left : right;
}
#define MAX(left, right) _Generic((left), \
int: max_int, double: max_double)((left), (right))
int main(void) {
printf("%d %.1f\n", MAX(3, 9), MAX(2.5, 7.0));
}
9 7.0
C++
main.cpp
#include <iostream>
template<class T>
T maximum(const T& left, const T& right) {
return left > right ? left : right;
}
int main() {
std::cout << maximum(3, 9) << ' '
<< maximum(2.5, 7.0) << '\n';
}
9 7
เปรียบเทียบ C และ C++
_Generic ต้องระบุ type ที่รองรับ ส่วน C++ template ใช้กับทุก type ที่มี operation ที่ต้องการ
C
C ใช้ prefix, callback, macro และ context struct
C++
ภาษาให้ abstraction ที่มี scope และ type-safe
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เขียนกลไก C ก่อน
- แทน manual cleanup ด้วย RAII
- ตรวจ allocation และ virtual dispatch