函数中定义函数的方法

#include<iostream>
#include<boost/function.hpp>
using namespace std;






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


void test01() {
	boost::function<int(int, int)> func;
	func = &g_func;
	cout << func(1, 2) << endl;
}

void test02() {
	class A {
	public:
		int classMemberFunc(int a) {
			return a + 1;
		}
	};


	boost::function<int(A&, int)>func;
	func = &A::classMemberFunc;
	A a;
	cout << func(a, 2) << endl;


	//class B {
	//public:
	//	int classMemberFunc(int a) {	//传值成员函数要const
	//		return a + 1;
	//	}
	//};

	//boost::function<int(B, int)>func1;
	//func1 = &B::classMemberFunc;
	//cout << func1(B(), 2) << endl;


	class some_class {
	public:
		int do_stuff(int i) const {		//要有const
			return i + 1;
		}
	};
	boost::function<int(some_class, int)> f;
	f = &some_class::do_stuff;
	cout << f(some_class(), 2) << endl;
}


void test03() {
	class A {
	public:
		int operator()(int a, int b) {
			return a + b;
		}
	};


	A a;
	boost::function<int(int, int)>func;
	func = a;
	cout << func(1, 2) << endl;
}



void test04() {
	auto func = [](int a, int b)->int {return a + b; };
	cout << func(1, 2) << endl;
}



void test05() {
	typedef struct A {
		static int func(int a, int b) {
			return a + b;
		}
	};

	cout << A::func(1, 2) << endl;
}



int main() {
	test01();	//boost function封装 自由函数
	test02();	//boost function封装 成员函数
	test03();	//boost function封装 函数对象
	test04();	//lambda
	test05();	//结构体静态函数




}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值