12

(ブースト)バインドを使用して引数を関数テンプレートにバインドすることは可能ですか?

// Define a template function (just a silly example)
template<typename ARG1, typename ARG2>
ARG1 FCall2Templ(ARG1 arg1, ARG2 arg2)
{
    return arg1 + arg2;
}

// try to bind this template function (and call it)
...
boost::bind(FCall2Templ<int, int>, 42, 56)(); // This works

boost::bind(FCall2Templ, 42, 56)(); // This emits 5 pages of error messages on VS2005
// beginning with: error C2780: 
//   'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type> 
//   boost::bind(M T::* ,A1)' : expects 2 arguments - 3 provided

boost::bind<int>(FCall2Templ, 42, 56)(); // error C2665: 'boost::bind' : none of the 2 overloads could convert all the argument types

アイデア?

4

2 に答える 2

18

boost::bindこの場合、関数テンプレートではなく関数ポインターを探しているため、そうは思いません。を渡すとFCall2Templ<int, int>、コンパイラは関数をインスタンス化し、関数ポインターとして渡されます。

ただし、ファンクターを使用して次のことができます

struct FCall3Templ {

  template<typename ARG1, typename ARG2>
  ARG1 operator()(ARG1 arg1, ARG2 arg2) {
    return arg1+arg2;
  }
};
int main() {
  boost::bind<int>(FCall3Templ(), 45, 56)();
  boost::bind<double>(FCall3Templ(), 45.0, 56.0)();
  return 0;
}

戻り値の型は入力に関連付けられているため、戻り値の型を指定する必要があります。リターンが変化しない場合はtypedef T result_type、テンプレートに追加するだけで、バインドが結果を判断できます

于 2011-08-12T11:47:00.153 に答える
4

関数参照を作成するとうまくいくようです:

int (&fun)(int, int) = FCall2Templ;
int res2 = boost::bind(fun, 42, 56)();

または:

typedef int (&IntFun)(int, int);
int res3 = boost::bind(IntFun(FCall2Templ), 42, 56)();

(GCCでテスト済み)

于 2011-08-12T13:54:20.657 に答える