我可以使用(boost)bind与函数模板吗?

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

有什么想法吗?

1
如果意图是多态行为,那么这个链接可能会引起兴趣:https://dev59.com/_2w05IYBdhLWcg3wxkqr - Luc Danton
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添加到模板中,以便bind可以确定结果是什么。


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上测试过)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接