栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++11包装器

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++11包装器

C++11包装器
  • 1. std::function
  • 2. std::bind

1. std::function
  • 当一个函数、仿函数、类成员函数、lambda表达式具有相同的参数和返回值时,可以用包装器进行统一包装调用。
#include 


int max(int a, int b)
{
	return a > b ? a : b;
}

typedef int (*pType)(int, int);

struct MaxFun
{
	int operator()(int a, int b)
	{
		return a > b ? a : b;
	}
};

class MaxClass 
{
public:
	int max(int a, int b)
	{
		return a > b ? a : b;
	}

	static int StaticMax(int a, int b)
	{
		return a > b ? a : b;
	}
};

int main()
{
	std::function f = max;  //包装一个函数,类似于函数指针的用法
	std::cout << "f = max:" << f(1, 2) << std::endl;

	pType pFunc = max;  //使用函数指针类型定义一个函数指针变量
	std::cout << "pFunc(1,2):" << pFunc(1, 2) << std::endl;
	
     //包装一个lambda表达式
	std::function fLamb = [](int a, int b)->int {return a > b ? a : b; };  

	std::cout << "fLamb(1,2):" << fLamb(1, 2) << std::endl;

	std::function fFunctor = MaxFun();  //包装一个仿函数
	std::cout << "fFunctor(1,2):" << fFunctor(1, 2) << std::endl;

    //包装类static类成员函数, 函数前可以取地址(&)也可以不取地址
	std::function fStaticClassMax = MaxClass::StaticMax;  
	std::cout << "fStaticClassMax(1,2):" << fStaticClassMax(1, 2) << std::endl;

    //包装类非static类成员函数,函数前必须取地址,且要注意this
	std::function fClassMax = &MaxClass::max;  
	std::cout << "fClassMax(1,2):" << fClassMax(MaxClass(), 1, 2) << std::endl;

	return 0;
}

运行结果:

f = max:2
pFunc(1,2):2
fLamb(1,2):2
fFunctor(1,2):2
fStaticClassMax(1,2):2
fClassMax(1,2):2
2. std::bind
#include 
#include 

class Print
{
public:
	void print(int a, int b, int c)
	{
		std::cout << "a = " << a << ",b = " << b << ",c = " << c << std::endl;
	}
};


int main()
{
	std::function f = &Print::print;
	f(Print(), 1, 2, 3);


	//std::function func = std::bind(&Print::print, Print(), std::placeholders::_2, std::placeholders::_1, std::placeholders::_3);
	auto func = std::bind(&Print::print, Print(), std::placeholders::_2, std::placeholders::_1, std::placeholders::_3);  // 将类调用与func绑定,调用时不需要传入类对象。另外可以通过绑定改变参数位置。
	func(1, 2, 3);


	return 0;
}

运行结果:

a = 1,b = 2,c = 3
a = 2,b = 1,c = 3
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/993704.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号