• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

函数适配器 mem_fn()

武飞扬头像
技术的微光
帮助1

函数适配器 mem_fn()

mem_fn()绑定成员函数,适配为非成员函数(如果额外实参,还是要bind)
是bind的一种变体,老代码中使用较多,新代码基本都使用lambda实现

实例代码

#include <functional>
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
using namespace std::placeholders;

class Language {
  private:
    string name;
  public:
    Language (const string& n) : name(n) {
    }
    void print () const {
        cout << name << " ";
    }
    void show (const string& postfix) const {
        cout  << name << postfix;
    }
    //...
};

int main()
{
    vector<Language> coll
            = { Language("C  "), Language("Rust"), Language("GO") };

    for_each (coll.begin(), coll.end(),
              bind(&Language::print,_1));	//使用_1不好看
    cout << endl;

    for_each( coll.begin(), coll.end(),
              mem_fn(&Language::print));	//直接使用mem_fn取函数地址
    cout << endl;

    for_each (coll.begin(), coll.end(),	
              bind(&Language::show,_1," * "));
    cout << endl;

    for_each (coll.begin(), coll.end(),
              bind(mem_fn(&Language::show), _1, " -> "));
              
    cout << endl;
    cout<<"\nlambda: "<<endl;

	//但所有的函数适配器都可以使用lamda表达式的完成,后续都用lamda表达式完成
    for_each(coll.begin(), coll.end(),
            [](const Language& lang) { lang.print(); });
    cout << endl;
    for_each(coll.begin(), coll.end(),
            [](const Language& lang) { lang.show(" -> "); });
    cout << endl;
}
学新通

编译及运行调试

kongcb@tcu-pc:~/testcode/lambda$ g   mem_fn.cpp -o mem_fn
kongcb@tcu-pc:~/testcode/lambda$ ./mem_fn
C   Rust GO 
C   Rust GO 
C   * Rust * GO * 
C   -> Rust -> GO -> 

lambda: 
C   Rust GO 
C   -> Rust -> GO -> 

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgkkgia
系列文章
更多 icon
同类精品
更多 icon
继续加载