TemplateとCのgeneric手法
Templateはtype-safeな実装を生成し、Cはmacro、void*、C11 _Genericを使います。
TemplateとCのgeneric手法とは?
Templateはtype-safeな実装を生成し、Cはmacro、void*、C11 _Genericを使います。
型に依存しないcompile-time codeを書きます。
重要なポイント
- 先にCの仕組みを理解します。
- RAIIとvalue semanticsでownershipを表現します。
- macroやcastよりtype-safeな抽象化を選びます。
Cと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は対応型を列挙します。C++ templateは必要operationを持つ任意の型に使えます。
C
Cはprefix、callback、macro、context構造体を使います。
C++
言語機能がscope付きtype-safeな抽象化を提供します。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- 最初にCの仕組みを書きます。
- 手動cleanupをRAIIに置き換えます。
- allocationとvirtual dispatchを確認します。