c++boost-bindboost-function

mismatch in the number of arguments passed to boost function using boost::bind


I am trying to create a Functor using boost function and bind, but i cant pass only a single argument to the destination function which has 3 arguments:

#include <boost/bind.hpp>
#include <boost/function.hpp>


template <typename Functor>
void foreach(Functor f) 
{
  int k;
  f(k);
}


class A
{
private:
void bar(int &a,int &b,int& c)
{}

void foo()
{
 int keys,predicate;
boost::function<void(int &,int&,int&)> functor_ ( boost::bind(
                &A::bar,
                this,
                boost::ref(keys),
                boost::ref(predicate),
                _1
                ));
 foreach(functor_);
 }

}; 

The error says:

binf.cpp: In instantiation of ‘void foreach(Functor) [with Functor = boost::function<void(int&, int&, int&)>]’:
binf.cpp:29:18:   required from here
binf.cpp:9:6: error: no match for call to ‘(boost::function<void(int&, int&, int&)>) (int&)’
   f(k);
      ^
In file included from /usr/include/boost/function/detail/maybe_include.hpp:28:0,
                 from /usr/include/boost/function/detail/function_iterate.hpp:14,
                 from /usr/include/boost/preprocessor/iteration/detail/iter/forward1.hpp:62,
                 from /usr/include/boost/function.hpp:64,
                 from binf.cpp:2:
/usr/include/boost/function/function_template.hpp:1048:7: note: candidate is:
 class function<BOOST_FUNCTION_PARTIAL_SPEC>
       ^
/usr/include/boost/function/function_template.hpp:761:17: note: boost::function3<R, T1, T2, T3>::result_type boost::function3<R, T1, T2, T3>::operator()(T0, T1, T2) const [with R = void; T0 = int&; T1 = int&; T2 = int&; boost::function3<R, T1, T2, T3>::result_type = void]
     result_type operator()(BOOST_FUNCTION_PARMS) const
                 ^
/usr/include/boost/function/function_template.hpp:761:17: note:   candidate expects 3 arguments, 1 provided

Of course, I want to pass only one argument, because I expect bind to take care of the other 2 args. I tried to search for my error but I couldn't find any(in a short call). Can you please help me find the problem? Thanks


Solution

  • You are creating boost::function<void(int&, int&, int&)>, i.e. function, that takes three arguments. Since you are using bind and want to call function with one argument it should be just boost::function<void(int&)>.