C++14で追加された汎用ラムダキャプチャ構文(ついでにジェネリックラムダ式も)を利用。
auto make_counter = [](auto init_val) {
return [count = init_val]() mutable {
return count++;
};
};
auto c1 = make_counter(1); // int型/初期値1
auto c2 = make_counter(3.14); // double型/初期値3.14
std::cout << c1() << std::endl; // 1
std::cout << c2() << std::endl; // 3.14
std::cout << c1() << std::endl; // 2
std::cout << c2() << std::endl; // 4.14
Inspired by