Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Ideas?

like image 880
Martin Ba Avatar asked Aug 12 '11 11:08

Martin Ba


People also ask

What is the purpose of boost bind?

Purpose. boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.

Does function template work with string?

The template function works for int and char, but not float and string.

What is _1 in boost :: bind?

_1 is a placeholder. Boost. Bind defines placeholders from _1 to _9 . These placeholders tell boost::bind() to return a function object that expects as many parameters as the placeholder with the greatest number.

What is a boost function?

boost::function makes it possible to define a pointer to a function with a specific signature. Example 40.1 defines a pointer f that can point to functions that expect a parameter of type const char* and return a value of type int .


1 Answers

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

like image 66
Dave S Avatar answered Nov 09 '22 14:11

Dave S