boost::coroutineを使ってみる
Boost.Coroutineを使うとC++でもコルーチンを使用することができます.
C++14になってからはラムダ式の引数に型推論が使えるようになり,
コルーチンの引数にラムダ式を使うことで,とても楽に書けるようになりました.
#include <iostream> #include <boost/coroutine/all.hpp> template< class T > using coroutine = boost::coroutines::coroutine< T >; //Coroutineで呼び出される関数 void cooperative( coroutine< int >::push_type & yield ) { int counter = 0; while( 1 ) { yield( ++counter ); } } int main() { coroutine< int >::pull_type generator( cooperative ); for( int i = 0; i < 10; ++i ) { std::cout << generator().get() << std::endl; } // 1 2 3 4 ... が出力 //**********************************************************// //ラムダ式バージョン coroutine< int >::pull_type double_gen( []( auto & yield ) { int counter = 0; while( 1 ) { yield( ++counter * 2 ); } } ); for( int i = 0; i < 10; ++i ) { std::cout << double_gen().get() << std::endl; } //2 4 6 8 ... が出力 //**********************************************************// return 0; }
Boost::coroutineはv1とv2の2つのバージョンが存在しており(2016年6月現在),v2ではv1のcaller_typeがpull_typeになっていたりと互換性が無いことに注意が必要です.