概要
- 関数ポインタでコールバックしてた感覚で、ローカル変数キャプチャしたラムダ式でコールバックがしたい
- 気分によって引数を省略したいときもあるよね!
うごいたコード
#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