c++ 成员函数指针的应用测试

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

using namespace std;

struct Memfn{
	Memfn(string s):s(s){
		
	}
	
	void operator()() const {
		std::cout << s << std::endl;
	}

	void world() const{
		std::cout << s << std::endl;
	}
private:
	string s;
};


void test(const Memfn& fn){
    fn.world();    
}

int main(int argc, char* argv[])
{
	vector<Memfn> vecs;
	vecs.push_back(string("hello"));
	vecs.push_back(string("world"));


	//

	//for_each(vecs.begin(), vecs.end(), [](string s){
	//	std::cout << s << std::endl;
	//});

	auto f = mem_fn(&Memfn::operator());

	auto v1 = Memfn("123");
	f(v1);
	test(v1);

	auto f2 = bind(&Memfn::operator(), std::placeholders::_1);

	function<void(const Memfn&)> f3 = &Memfn::world;

	for_each(vecs.begin(), vecs.end(), f3);


	return 0;
}


posted @ 2021-06-29 22:38  iwetuan  阅读(47)  评论(0)    收藏  举报