#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