使用 boost::bind 传递给 boost 函数的参数数量不匹配

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

我正在尝试使用 boost 函数和绑定创建一个 Functor,但我不能只将一个参数传递给具有 3 个参数的目标函数:

#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_);
 }

}; 

错误说:

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

当然,我只想传递一个参数,因为我希望 bind 处理其他 2 个参数。我试图搜索我的错误,但我找不到任何错误(在一个简短的电话中)。 你能帮我找到问题吗? 谢谢

您正在创建 boost::function<void(int&, int&, int&)>,即采用三个参数的函数。由于您正在使用 bind 并希望使用一个参数调用函数,因此它应该只是 boost::function<void(int&)>.