为非静态成员函数创建unary_function函数

create an unary_function functor for non-static member function

本文关键字:函数 function unary 创建 静态成员      更新时间:2023-10-16

代码应该解释了我的困难。虽然代码本身毫无意义,但我计划在MyClass中添加容器,并使用带有成员函数的算法。

#include <cstdlib>
#include <algorithm>
#include <functional>
using namespace std;
class MyClass
{
    public:
        MyClass() { a = 0; }
        ~MyClass() {}
    private:
        int a;
        bool tiny_test (int);
        int Func();
};
bool MyClass::tiny_test (int b)
{
    return a == b;
}
int MyClass::Func()
{
    // does not compile
    (mem_fun(&MyClass::tiny_test))(this);
    // commented below is another attempt, also no success
    //mem_fun1_t<bool, MyClass, int> tmp_functor = mem_fun(&MyClass::tiny_test);
    //tmp_functor(this);
    return 0;
}
int main(int argc, char** argv)
{
    return 0;
}

非常感谢!顺便说一句,我没有使用静态成员函数,只是因为我相信它必须适用于非静态成员函数。P.S. Eric, Jarod42,感谢您的及时回复!

bool MyClass::tiny_test (int b)
{                     // ^^^^^ You missed this argument
    return a == b;
}

试试这个:

// Supply one more argument. E.g., 3
(mem_fun(&MyClass::tiny_test))(this, 3);