lambdaとの格闘(上手投げ)
ふと考えた。c++0xのlambdaってfunctorに展開されるんだからthrow出来るのではないか。書いてみた。
#include <iostream> #include <string> #include <functional> using namespace std; auto except_func( void ) -> void { throw []( void ) -> string { return "exception"; }; } auto main( void ) -> int { try { except_func(); } catch ( function< string ( void ) > lmd ) { cout << lmd() << endl; } catch ( ... ) { cout << "invalid exception type" << endl; } return 0; }
結果。だめだった。
型はあってると思うんだがなー。未実装とか?
速攻追記:
#include <iostream> #include <string> #include <functional> using namespace std; auto except_func( void ) -> void { throw function< string ( void ) >( []( void ) -> string { return "exception"; } ); } auto main( void ) -> int { try { except_func(); } catch ( function< string ( void ) > lmd ) { cout << lmd() << endl; } catch ( ... ) { cout << "invalid exception type" << endl; } return 0; }
こうしたらいけた。んー難しいが、lambdaを投げられるとなると相当例外が役立つな。
単なる情報だけだった例外が再起戦略とか継続処理とかいろいろとトリッキーになる。
まぁ今までも出来たんですけどね。こっちの方が楽じゃん。行少ないし直感的だし。