繁体   English   中英

mem_fn到成员对象的功能

[英]mem_fn to function of member object

我正在修改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吗?

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

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

据我所知, std::mem_fn()或多或少是过时的,因为lambda表达式 例如

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

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

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

也许这就是你想要的

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

因为无论如何都没有指定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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM