Boost1.50.0でリリースされた、Boost.Functional/Overloaded Function
複数の異なる関数を、ひとつの関数オブジェクトにオーバーロードすることができるライブラリです。
同目的で異なる名前、引数の型を持つ関数のあるC時代のライブラリを使うときに重宝しそうです。
#include <iostream> #include <sstream> #include <boost/functional/overloaded_function.hpp> std::string concat_s(const std::string& a, const std::string& b){ std::string c = a; c.append(b); return c; } int concat_i(int a, int b){ std::stringstream ss; ss << a; ss << b; int c; ss >> c; return c; } int main(){ boost::overloaded_function< std::string(const std::string&, const std::string&), int(int, int) > concat(concat_s, concat_i); std::string str1 = "わぁいBoost.Functional/OverloadedFunction "; std::string str2 = "あかりBoost.Functional/OverloadedFunction大好き"; std::cout << concat(65, 535) << std::endl; std::cout << concat(str1, str2) << std::endl; return 0; }
Output:
65536 わぁいOverloadedFunction あかりOverloadedFunction大好き
オーバーロードできる関数の数(=テンプレート引数の数)はデフォルトでは5つまでです。
それより多くの関数を扱いたい場合、もしくはそれより少ない数に制限したい場合は、ライブラリをインクルードする前に、マクロBOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAXを定義することで、最大値(2以上)を指定します。
//最大値を10に設定 #define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_OVERLOAD_MAX 10 #include <boost/functional/overloaded_function.hpp>
オーバーロードする関数の引数の最大数も、デフォルトでは5に制限されています。
最大値の設定にはマクロBOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAXを定義します。
#define BOOST_FUNCTIONAL_OVERLOADED_FUNCTION_CONFIG_ARITY_MAX 7
ここでは関数しか使いませんでしたが、ラムダ式、operator()を定義したクラスのインスタンス、boost::functionなどの関数オブジェクトもオーバーロードできます。