我可以用一个函数模板(升压)绑定? [英] Can I use (boost) bind with a function template?

查看:128
本文介绍了我可以用一个函数模板(升压)绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能将参数绑定到一个函数的模板的用的(升压)绑定

Is it possible to bind arguments to a function template with (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

想法?

推荐答案

我不这么认为,只是因为在这种情况下,的boost ::绑定正在寻找函数指针,而不是一个函数模板。当您在传递 FCall2Templ&LT; INT,INT方式&gt; ,编译器实例化功能,它是作为一个函数指针传递

I don't think so, only because boost::bind in this case is looking for a function pointer, not a function template. When you pass in FCall2Templ<int, int>, the compiler instantiates the function and it is passed as a function pointer.

不过,你可以使用仿函数以下

However, you can do the following using a functor

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 result_type的牛逼来的模板,这样绑定可以确定结果是什么

You have to specify the return type, since the return type is tied to the inputs. If the return doesn't vary, then you can just add typedef T result_type to the template, so that bind can determine what the result is

这篇关于我可以用一个函数模板(升压)绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆