c++ - 将 mem_fun 与具有多个参数的函数一起使用

标签 c++ function boost function-pointers

我正在尝试使用 boost:function 类。在下面的示例中,对于 foo() 调用,一切正常,但如果我想对 sum() 函数执行相同操作,gcc 编译器会提示这一行:

_f2 = std::bind1st(std::mem_fun(f), x);

mem_func 是否只接受带有一个参数的函数(除了指向我绑定(bind)的类对象的指针)?如果可以的话我还可以使用什么其他功能?或者我该如何更改这行代码?

我认为有一种使用 boost:bind() 的方法,但我还没有弄清楚如何在这种情况下使用它。

完整代码如下:

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

class X
{
public:

    int foo(int i){return i;};
    int sum(int i, int j) {return i+j;};
};

class Func
{

public:

   Func(X *x,  int (X::* f) (int))
   {
      _f1 = std::bind1st(std::mem_fun(f), x);
      std::cout << _f1(5); // Call x.foo(5)
   };

   Func(X *x,  int (X::* f) (int, int))
   {
      _f2 = std::bind1st(std::mem_fun(f), x);
      std::cout << _f2(5, 4); // Call x.foo(5,4)
   };

private:

    boost::function<int (int)> _f1;
    boost::function<int (int, int)> _f2;
};


int main()
{

    X x;

    Func func1(&x, &X::foo);
    Func func2(&x, &X::sum);

    return 0;
}

最佳答案

您可以使用 boost 绑定(bind):

_f2 = boost::bind(f, x, _1, _2);

关于c++ - 将 mem_fun 与具有多个参数的函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6626467/

相关文章:

C++ - 获取整数位的大小

c++ - 错误 : name lookup of 'i' changed for ISO 'for' scoping

c++ - 普通的右值引用和 std::forward 返回的有什么区别?

javascript - 如何从javascript中的onclick访问vue函数?

c++ - boost 是否使用 C++11 "inline namespaces"来避免运行时出现 ABI 不兼容错误?

c++ - Boost::GIL bits8* 到 gray8_ptr_t 没有 reinterpret_cast?

c++ - 使用 size() 返回当前在我的类中的元素数 (c++)

perl - 如何打印到 Perl 中的变量?

c++ - 使用嵌套结构将结构作为引用传递的错误

c++ - boost 侵入式交换