首页 > 其他分享 >std::mem_fn

std::mem_fn

时间:2022-11-09 22:26:08浏览次数:39  
标签:std const 传入 mem Age ages fn

目录

std::mem_fn

1. 不支持的场景

1.1 不支持全局函数

1.2 不支持类protected访问权限的成员(函数或数据)

1.3 不支持类private访问权限的成员(函数或数据)

2. 支持的场景

2.1 传入类对象

2.2 传入引用对象

2.3 传入右值

2.4 传入对象指针

2.5 传入智能指针std::shared_ptr

2.6 传入智能指针std::unique_ptr

2.7 传入派生类对象

2.8 带参数的成员函数

3. 场景示例代码

#include <functional>
#include <iostream>

int Add(int a, int b)
{
    return a + b;
}

class Age
{
public:
    Age(int default = 12) : m_age(default)
    {}

    bool compare(const Age& t) const
    {
        return m_age < t.m_age;
    }

    void print() const
    {
        std::cout << m_age << ' ';
    }

    int m_age;

protected:
    void add(int n)
    {
        m_age += n;
    }

private:
    void sub(int m)
    {
        m_age -= m;
    }
};

class DerivedAge : public Age
{
public:
    DerivedAge(int default = 22) : Age(default)
    {}
};

int main(int argc, char* argv[])
{
    // 0.不支持的示例
    {
        // 1.不支持全局函数
        // auto globalFunc = std::mem_fn(Add); // ERROR: 语法无法通过
        // 2.不支持类protected访问权限的函数
        // auto addFunc = std::mem_fn(&Age::add); // ERROR: 语法无法通过
        // 3.不支持类private访问权限的函数
        // auto subFunc = std::mem_fn(&Age::sub); // ERROR: 语法无法通过
    }
    // 1.成员函数示例
    {
        auto memFunc = std::mem_fn(&Age::print);

        // 方式一:传入类对象
        Age obja{ 18 };
        memFunc(obja);

        Age& refObj = obja;
        refObj.m_age = 28;
        // 方式二:传入引用对象
        memFunc(refObj);

        // 方式三:传入右值
        Age objb{ 38 };
        memFunc(std::move(objb));

        // 方式四:传入对象指针
        Age objc{ 48 };
        memFunc(&objc);

        // 方式五:传入智能指针std::shared_ptr
        std::shared_ptr<Age> pAge1 = std::make_shared<Age>(58);
        memFunc(pAge1);

        // 方式六:传入智能指针std::unique_ptr
        std::unique_ptr<Age> pAge2 = std::make_unique<Age>(68);
        memFunc(pAge2);

        // 方式七:传入派生类对象
        DerivedAge aged{ 78 };
        memFunc(aged);
        
        // 方式八:带参数成员函数
        auto memFuncWithParams = std::mem_fn(&Age::compare);
        std::cout << memFuncWithParams(Age{ 25 }, Age{ 35 }) << std::endl;
    }

    std::cout << std::endl;

    // 2.成员变量示例
    {
        auto memData = std::mem_fn(&Age::m_age);

        // 方式一:传入类对象
        Age obja{ 19 };
        std::cout << memData(obja) << ' ';

        Age& refObj = obja;
        refObj.m_age = 29;
        // 方式二:传入引用对象
        std::cout << memData(refObj) << ' ';

        // 方式三:传入右值
        Age objb{ 39 };
        std::cout << memData(std::move(objb)) << ' ';

        // 方式四:传入对象指针
        Age objc{ 49 };
        std::cout << memData(&objc) << ' ';

        // 方式五:传入智能指针std::shared_ptr
        std::shared_ptr<Age> pAge1 = std::make_shared<Age>(59);
        std::cout << memData(pAge1) << ' ';

        // 方式六:传入智能指针std::unique_ptr
        std::unique_ptr<Age> pAge2 = std::make_unique<Age>(69);
        std::cout << memData(pAge2) << ' ';

        // 方式七:传入派生类对象
        DerivedAge aged{ 79 };
        std::cout << memData(aged) << ' ';
    }

    return 0;
}

/* run output:
18 28 38 48 58 68 78 1
19 29 39 49 59 69 79
*/

4. 应用示例

4.1 以前写法

4.2 使用std::mem_fn写法

4.3 示例代码

#include <functional>
#include <iostream>
#include <algorithm>
#include <vector>

class Age
{
public:
    Age(int v) : m_age(v)
    {}

    bool compare(const Age& t) const
    {
        return m_age < t.m_age;
    }

    void print() const
    {
        std::cout << m_age << ' ';
    }

    int m_age;
};

bool compare(const Age& t1, const Age& t2)
{
    return t1.compare(t2);
}

int main(int argc, char* argv[])
{
    // 以前写法
    {
        std::vector<Age> ages{ 1, 7, 19, 27, 39, 16, 13, 18 };
        std::sort(ages.begin(), ages.end(), [&](const Age& objA, const Age& objB) {
            return compare(objA, objB);
            });
        for (auto item : ages)
        {
            item.print();
        }
        std::cout << std::endl;
    }
    // 利用std::mem_fn写法
    {
        std::vector<Age> ages{ 100, 70, 290, 170, 390, 160, 300, 180 };
        std::sort(ages.begin(), ages.end(), std::mem_fn(&Age::compare));
        std::for_each(ages.begin(), ages.end(), std::mem_fn(&Age::print));
        std::cout << std::endl;
    }

    return 0;
}

/* run output:
1 7 13 16 18 19 27 39
70 100 160 170 180 290 300 390
*/

标签:std,const,传入,mem,Age,ages,fn
From: https://www.cnblogs.com/Braveliu/p/16875374.html

相关文章

  • POJ 3580 SuperMemo
    DescriptionYourfriend,JacksonisinvitedtoaTVshowcalledSuperMemoinwhichtheparticipantistoldtoplayamemorizinggame.Atfirst,thehosttells......
  • Nginx:代理FastDFS实现文件访问
    搭建​​FastDFS​​分布式文件系统参考下面这篇博客:​​分布式:搭建FastDFS分布式文件系统​​安装fastdfs-nginx-module安装​​fastdfs-nginx-module​​​也是只在​​st......
  • vue运行或打包报错Ineffective mark-compacts near heap limit Allocation failed-Jav
    vue运行或打包报错:Ineffectivemark-compactsnearheaplimitAllocationfailed-JavaScriptheapoutofmemory问题:用npmrundev启动项目或者npmrunbuild打包会报em......
  • LINUX 安装 NGINX ‘STRUCT CRYPT_DATA’ HAS NO MEMBER NAMED ‘CURRENT_SALT’ 解决
    出现这个问题一般不是Nginx的版本高就是服务器版本高的问题解决办法:在nginx安装文件夹下输入[[email protected]]#vimsrc/os/unix/ngx_user.c进去编辑找到红......
  • [15-445]Database Storage related memo 1
    最先的一部分还是介绍存储介质速度层级 总的来说就是cpu>memory>disk但是究竟快多少呢?  我觉得这里只需要记住一个常用的关键论点,内存约比ssd快150倍......
  • innodb引擎,myisam引擎,memory引擎区别【最新版】
    innodb引擎.frm表结构文件.idb数据和索引文件innodb引擎执行count(*)的时候,需要把数据一行一行地从引擎里面读出来,累积计数事务型数据库首选,支持事务ACID支持行......
  • 第2-1-4章 SpringBoot整合FastDFS文件存储服务
    目录5SpringBoot整合5.1操作步骤5.2项目依赖5.3客户端开发5.3.1FastDFS配置5.3.2FastDFS配置类5.3.3文件工具类5.3.4文件上传配置5.3.5配置Swagger25.3.6API接口......
  • memtest86+4.20流程分析
       公版ubuntu自带memtest86+内存测试工具,出于工作需要,分析了其工作流程记录于此。   分析一个陌生的程序,当然得先找入口入口函数,很可惜main()/_start之类的都找到,......
  • TestDeadLock
    publicclassTestDeadLockimplementsRunnable{intb=100;//成员变量,一个方法改变了值就是永远改变了publicsynchronizedvoidm1()throwsException{b=1000......
  • leveldb学习笔记之六——db/memtable.h
    db数据在内存中的存储格式,写操作的数据都会先写到memtable中类classMemTable{public://构造函数,不允许隐式转换,参数为内部key比较器explicitMemTable(constInte......