LoginSignup
1
1

More than 3 years have passed since last update.

コールバックにラムダ式を渡したいけど引数省略もしたい

Posted at

概要

  • 関数ポインタでコールバックしてた感覚で、ローカル変数キャプチャしたラムダ式でコールバックがしたい
  • 気分によって引数を省略したいときもあるよね!

うごいたコード

#include <iostream>
#include <functional>
using namespace std;

//! @param[in] cb 省略可。進捗のパーセンテージをコールバックします。
//! @param[out] なんか処理の計算結果。
int doSomething(const std::function<void(int)>& cb = nullptr)
{
    // なんか処理

    if(cb) { cb(10); }

    // なんか処理

    if(cb) { cb(20); }

    // なんか処理

    if(cb) { cb(40); }

    // なんか処理

    if(cb) { cb(60); }

    // なんか処理

    if(cb) { cb(80); }

    return 10000;
}

int main(void)
{
    // コールバック処理。進捗をコンソールに表示。
    char percent[] = "%";
    auto callback = [&](int progress)
    {
        cout << "progress: " << progress << percent << endl;
    };

    cout << "CASE1 -- With callback" << endl;
    int result = doSomething(callback);
    cout << "result = " << result << endl;

    cout << "\nCASE2 -- Without callback" << endl;
    cout << "result = " << doSomething() << endl;
}
console
CASE1 -- With callback
progress: 10%
progress: 20%
progress: 40%
progress: 60%
progress: 80%
result = 10000

CASE2 -- Without callback
result = 10000
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1