動的に複数の型を返す関数
boost.variant を使用すれば、簡単にエミュレート出来ました。
#include <iostream> #include <string> #include <utility> #include <boost/variant.hpp> typedef boost::variant<int, std::string, std::pair<int, std::string> > var_type; var_type func(int n){ switch(n){ case 0: return std::string("string"); case 1: return 10; default: return std::make_pair(10, "string"); } } struct disp{ typedef void result_type; template<typename T> void operator()(T t) const{ std::cout << t << std::endl; } void operator ()(std::pair<int, std::string> t) const{ std::cout << t.first << ":" << t.second << std::endl; } }; int main(){ var_type v = func(0); boost::apply_visitor(disp(), v); v = func(1); boost::apply_visitor(disp(), v); v = func(2); boost::apply_visitor(disp(), v); return 0; }
[出力]
string 10 10:string
boost.variant 面白い。
which() と get<>() を使用すれば、直接中身を取得出来ますが、apply_visitor を使用したほうがラクチンだと思います。
あと使用してみて初めて、type_switch が欲しいと思いました。
[boost]
ver 1.46.1
[参照]
http://www.kmonos.net/alang/boost/classes/variant.html