Can I use (boost) bind with a function template?

孤街醉人 提交于 2019-11-28 00:51:49

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;
}

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 seems to work if you create a function reference:

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

Or:

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

(Tested on GCC)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!