【问题标题】:Can I use (boost) bind with a function template?我可以将(增强)绑定与功能模板一起使用吗?
【发布时间】:2011-10-25 18:02:05
【问题描述】:

是否可以使用(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

想法?

【问题讨论】:

  • 如果意图是多态行为,那么this 可能是有意义的。

标签: c++ boost boost-bind function-templates


【解决方案1】:

我不这么认为,只是因为在这种情况下boost::bind 是在寻找函数指针,而不是函数模板。当您传入FCall2Templ&lt;int, int&gt; 时,编译器会实例化该函数并将其作为函数指针传递。

但是,您可以使用仿函数执行以下操作

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,以便绑定可以确定结果是什么

【讨论】:

    【解决方案2】:

    如果你创建一个函数引用,它似乎可以工作:

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

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      相关资源
      最近更新 更多