【问题标题】:create an unary_function functor for non-static member function为非静态成员函数创建一个 unary_function 仿函数
【发布时间】:2015-07-29 23:38:47
【问题描述】:

代码应该可以解释我的困难。虽然代码本身没什么意义,但我打算在 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;
}

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

【问题讨论】:

  • 请注意,std::mem_fun 自 C++11 以来已被弃用,并在 C++17 中被删除(支持 std::mem_fnstd::bind)。

标签: c++ stl functor


【解决方案1】:
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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2018-09-18
    • 1970-01-01
    • 2013-05-03
    相关资源
    最近更新 更多