mem_fn到成员对象的功能 [英] mem_fn to function of member object

查看:59
本文介绍了mem_fn到成员对象的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在修改std::mem_fn,无法将其绑定到结构成员(更深一层)的数据/功能.

I was tinkering around with the std::mem_fn and couldn't manage to bind it to data/functions of an member of a struct (one layer deeper).

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

I hope that the code shows the problem better than I can describe it, because I'm not familiar with the terminology.

#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吗?

Question: Is it possible to make these binds? Do I need std::bind for this?

推荐答案

根据规范,

According to the specification, std::mem_fn() takes as argument a member function pointer, i.e.

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

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

As far as I'm aware, std::mem_fn() is more or less obsolete, since lambda expressions. For example

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

这篇关于mem_fn到成员对象的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆