可调用对象包装器-std::function

std::function就是一个类模板,除了类函数之外,可以容纳所有的可调用对象。

可调用对象的定义:

1.函数指针

2.仿函数(operator)

3.可以被转化成函数指针的对象

4.类函数

#include <iostream>
#include <functional>

void Test_1(void)
{
	std::cout << "Test_1" << std::endl;
}

class TestClass_1
{
public:
	static int Test_2(int n)
	{
		std::cout << "Test_2 add 3 is " << n + 3 << std::endl;
		return n;
	}
};

class TestClass_2
{
public:
	float operator()(float n)
	{
		std::cout << "operator add 5.6 is " << n + 5.6 << std::endl;
		return n;
	}
};

int main(int argc, char* argv[])
{
	std::function<void(void)> Func_1 = Test_1;
	Func_1();

	std::function<int(int)> Func_2 = TestClass_1::Test_2;
	std::cout << Func_2(5) << std::endl;

	TestClass_2 This;
	std::function<float(float)> Func_3 = This;
	std::cout << Func_3(5.3f) << std::endl;

	std::cin.get();
	return 1;
}

std::function可以取代函数指针,可以作为回调函数使用,如下

#include <iostream>
#include <functional>

void ThreadFunction(int nValue,const std::function<void(int)>& fn)
{
	if (nValue % 2)
	{
		fn(nValue);
	}
}

void PrintNumber(int nValue)
{
	std::cout << "Number is " << nValue << std::endl;
}

int main(int argc, char* argv[])
{
	for (int i = 5; i < 20; i++)
		ThreadFunction(i, PrintNumber);

	std::cin.get();
	return 1;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值