C++ LambdaとCのclosure手法
Lambdaはcapture可能な無名callableを作り、Cはcontextを明示的に渡します。
C++ LambdaとCのclosure手法とは?
Lambdaはcapture可能な無名callableを作り、Cはcontextを明示的に渡します。
Callbackへcontextを渡します。
重要なポイント
- 先にCの仕組みを理解します。
- RAIIとvalue semanticsでownershipを表現します。
- macroやcastよりtype-safeな抽象化を選びます。
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はthresholdをvalue captureし型情報を保持します。
C
Cはprefix、callback、macro、context構造体を使います。
C++
言語機能がscope付きtype-safeな抽象化を提供します。
練習課題
両方を実行して変更し、言語ごとの保証を確認します。
- 最初にCの仕組みを書きます。
- 手動cleanupをRAIIに置き換えます。
- allocationとvirtual dispatchを確認します。