C++14のgeneric lambdaを使ってみる(ほんとに便利なのは)

前回書いた,C++14のgeneric lambdaを使ってみるの補足.
いろんな型につかえること.Generic.
どういうことかというと,std::vectorやstd::vectorなど,どんな型にも使えるような1つのラムダ式を作れる.
例えば,これまでのだと,

std::vector<int> idata;
std::vector<double> ddtata;
auto fi = [](int x){ std::cout << x << std::endl; };
auto fd = [](double x){ std::cout << x << std::endl; };
std::for_each(idata.begin(), idata.end(), fi);
std::for_each(ddata.begin(), ddata.end(), fd);

とか,

std::vector<int> idata;
std::vector<double> ddata;
auto fi = [](int x, int y){ return x > y; };
std::sort(idata.begin(), idata.end(), fi);
auto fd = [](int x, int y){ return x > y; };
std::sort(idata.begin(), idata.end(), fd);

という風に,扱う配列の型ごとに用意しないといけなかった.
それが,C++14からは,まとめて1つにできる.上の例だと,

std::vector<int> idata;
std::vector<double> ddtata;
auto f = [](auto x){ std::cout << x << std::endl; };
std::for_each(idata.begin(), idata.end(), f);
std::for_each(ddata.begin(), ddata.end(), f);

std::vector<int> idata;
std::vector<double> ddata;
auto f = [](auto x, auto y){ return x > y; };
std::sort(idata.begin(), idata.end(), f);
std::sort(idata.begin(), idata.end(), f);

となる.

コメントする