成员函数作为可调用对象

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

struct Character
{
	void fixedHealth()
	{
		cout << 100 << endl;
	}

	void health(int val)
	{
		cout << val << endl;
	}
};

//参考effective stl 41
void test01()
{
	//Character::fixedHealth 需要一个参数 this
	Character cha1;
	Character cha2;
	vector<Character> vw;
	vw.push_back(cha1);
	vw.push_back(cha2);
	//vector<Character *> lpw同样适用mem_fn;
	for_each(vw.begin(), vw.end(), mem_fn(&Character::fixedHealth));
}

void test02()
{
	//Character::health 需要两个参数 (this ,int)
	vector<int> vec = {1,2,3};
	Character cha;
	for_each(vec.begin(), vec.end(), bind(&Character::health, cha, _1));
}

int main()
{
	test01();
	test02();

	return 0;
}

cppreference.com

bind使用

struct Foo {
    void print_sum(int n1, int n2)
    {
        std::cout << n1+n2 << '\n';
    }
    int data = 10;
};
int main()
{
    using namespace std::placeholders;  // 对于 _1, _2, _3...
	
	// 绑定指向成员函数指针
    Foo foo;
    auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);
    f3(5);	//100
}

mem_fn使用

#include <functional>
#include <iostream>
 
struct Foo {
    void display_greeting() {
        std::cout << "Hello, world.\n";
    }
    void display_number(int i) {
        std::cout << "number: " << i << '\n';
    }
    int data = 7;
};
 
int main() {
    Foo f;
 
    auto greet = std::mem_fn(&Foo::display_greeting);
    greet(&f);
 
    auto print_num = std::mem_fn(&Foo::display_number);
    print_num(&f, 42);
 
    auto access_data = std::mem_fn(&Foo::data);
    std::cout << "data: " << access_data(&f) << '\n';
}
//输出:
//Hello, world.
//number: 42
//data: 7
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值