mem_fn到成员对象的功能

时间:2017-06-19 08:31:26

标签: c++ bind member-function-pointers member-variables

我正在修补std::mem_fn,无法将其绑定到结构成员的数据/函数(更深层)。

我希望代码能够比我描述的更好地展示问题,因为我对术语并不熟悉。

#include <functional>

struct Int
{
    Int(int _x = 0) : x(_x) {}
    int GetInt() const { return x; }
    int x;
};

struct IntWrapper
{
    IntWrapper(int _x = 0) : test(_x) {}
    int GetWrappedInt() const { return test.GetInt(); }
    Int test;
};

int main()
{    
    IntWrapper wrapper{ 123 };

    auto x = std::mem_fn(&IntWrapper::GetWrappedInt);
    //auto y = std::mem_fn(&IntWrapper::test.GetInt); // ERROR
    //auto z = std::mem_fn(&IntWrapper::test.x); // ERROR

    int a = x(wrapper);
    //int b = y(wrapper);
    //int c = z(wrapper);

    //std::cin.ignore();

    return 0;
}

错误消息如下:

error C2228: left of '.GetInt' must have class/struct/union
error C2672: 'std::mem_fn': no matching overloaded function found
error C3536: 'y': cannot be used before it is initialized
error C2064: term does not evaluate to a function taking 1 arguments

问题: 是否有可能做出这些约束?我需要std::bind吗?

3 个答案:

答案 0 :(得分:2)

根据规范,std::mem_fn()将成员函数指针作为参数,即

auto y = std::mem_fn(&Int::GetInt);
auto b = y(wrapper.test);

据我所知,std::mem_fn()或多或少已过时,因为lambda expressions。例如

auto y = [](IntWrapper const&wrapper) { return wrapper.test.GetInt(); };
auto b = y(wrapper);    // note: no need to get hold of member 'test'

答案 1 :(得分:2)

您的语法错误,&IntWrapper::test是指向成员的指针。

我从未见过&IntWrapper::test.GetInt,我甚至不知道如何解析它。

也许这就是你想要的

auto y = std::mem_fn(&decltype(IntWrapper::test)::GetInt);
auto b = y(wrapper.test);

答案 2 :(得分:2)

因为无论如何都没有指定std::mem_fn的返回类型,我只是看不出使用它而不是某些lambda函数的原因:

auto x = [&wrapper]{  return wrapper.GetWrappedInt(); };
int a = x();

或者:

auto x = [](const IntWrapper& wrapper){ return wrapper.GetWrappedInt(); };
int a = x(wrapper);

我甚至认为这些更好,因为编译器可以有更好的优化机会。