12

是否可以使用(boost) bind将参数绑定到函数模板

// 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 回答