引数の型だけ違う関数オブジェクトの処理をtemplateで切り分ける−1
記事のまとめ
続いたのでまとめておく。
本文
クラスの型自身での条件分岐はよく書いてるけれども引数の型ってのでどうやるんだろうというのをうだうだ書いてたメモ。
メンバ関数の引数をTagに使ってるTag dispatch感ある。
#include <iostream> #include <vector> //1引数をとるメンバ関数用のテンプレート&Arg_の型で処理を切り分け template <typename T_, typename Arg_> struct ClassMethod{typedef void (T_::*Function)(Arg_);}; template<typename T_> void operatorInner(T_ t, std::vector<double> x, typename ClassMethod<T_, std::vector<double>>::Function){t(x);} template<typename T_> void operatorInner(T_ t, std::vector<double> x, typename ClassMethod<T_, double>::Function){ t(x[0]);} //引数の型が違うクラス struct A{ void operator()(double x){ std::cout << "I'm class A:" << x << std::endl; } }; struct B{ void operator()(std::vector<double> x){ std::cout << "I'm class B:" << x[0] << ", " << x[1] << ", " << x[2] << std::endl; } }; //中でA・Bクラスを使う適当なクラス template<typename T_> struct Moge { Moge(T_ x) : x_(x){} void operator()(std::vector<double> x){operatorInner(x_, x, &T_::operator());} T_ x_; }; //メイン int main() { std::vector<double> xxx = { 1, 2, 3 }; B b; Moge<B> x1(b); x1(xxx); A a; Moge<A> x2(a); x2(xxx); return 0; }
実行結果
I'm class B:1, 2, 3 I'm class A:1