モダンC++とCでの代替手法

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を確認します。