C++ 回调函数

c++ 回调函数

c++中,指针存储的是一个固定长度的地址。至于地址中的数据类型是什么,这根据指针的类型来确定。c++可以用 [类型] *[变量名]的形式来定义指向变量的指针,也可以类似地定义指向函数的指针。

以hello world程序为例

参考C++回调函数使用心得

直接执行的方式

#include <iostream>
#include <string>
using namespace std;

int main()
{
	cout << "hello world" << endl;
	return 0;
}

将hello world以函数形式封装

void invoke(string s)
{
	cout << s << endl;
}

int main()
{
	invoke("hello world");
	return 0;
}

以回调函数的形式

void invoke(string s)
{
	cout << s << endl;
}

int main()
{
	void(*fp)(string s);	//定义了一个变量fp,其数据类型是:参数为string s,返回值为void的函数指针
	fp = invoke;			//为函数指针变量fp赋值
	fp("hello world");		//调用函数指针
	return 0;
}

这段代码使用了fp这样一个函数指针变量,指向invoke函数。C++支持函数名invoke来调用函数。也可以使用函数指针来调用它所指向的那个函数,此时,程序会隐式地将函数指针解引用。也就是说,下面这种写法也是合法的。

void invoke(string s)
{
	cout << s << endl;
}

int main()
{
	void(*fp)(string s);	//定义了一个变量fp,其数据类型是:参数为string s,返回值为void的函数指针
	fp = invoke;			//为函数指针变量fp赋值
	(*fp)("hello world");	//对函数指针解引用后再进行调用
	return 0;
}

使用宏定义来声明函数指针

更常见也更规范的做法是,使用宏定义来声明函数指针。

声明的格式为 typedef [返回值类型] (*[函数指针类型名])([参数列表])。通过这种方法,可以定义一种新的数据类型,即定义一种函数指针,规定其参数列表和返回值类型。

typedef void(*FP)(string s);	//宏定义 定义了一个确定类型(参数和返回值)的函数指针
void invoke(string s)
{
	cout << s << endl;
}

int main()
{
	FP fp;				//声明变量fp,其数据类型为FP
	fp = invoke;		//将同种类型(参数和返回值)的函数,赋值给函数指针fp,此处赋值操作将函数隐式转换为函数指针
	//fp = &invoke;		//这种写法也是合法的
	fp("hello world");	//通过函数指针实现函数调用
	return 0;
}

C++中可调用对象的虽然都有一个比较统一的操作形式,但是定义方法各种各样,如普通函数、lambda表达式、functor仿函数等。这样就导致使用统一的方式保存可调用对象或者传递可调用对象时,会十分繁琐。C++11中提供了std::function和std::bind统一了可调用对象的各种操作。

下面是另外一种使用std::function来定义回调函数的方式,其定义格式为
typedef function<[返回值类型](参数类型)> [函数指针类型名]。参考知乎专栏

#include <iostream>
#include <string>
#include <functional>
using namespace std;

typedef function<void(string)> FP;//宏定义 定义了一个确定类型(参数和返回值)的函数指针
void invoke(string s)
{
	cout << s << endl;
}

int main()
{
	FP fp;				//声明变量fp,其数据类型为FP
	fp = invoke;		//将同种类型(参数和返回值)的函数,赋值给函数指针fp,此处赋值操作将函数隐式转换为函数指针
	//fp = &invoke;		//这种写法也是合法的
	fp("hello world");	//通过函数指针实现函数调用
	return 0;
}

在类中调用

std::bind

首先介绍一下std::bind函数。这个函数的作用是,为函数的特定参数绑定一个默认值,其返回值仍然是一个函数。以下面的代码片段为例。

#include <iostream>
#include <string>
#include <functional>
using namespace std;

void TestFun(int a, char c, float f)
{
	cout << a << endl;
	cout << c << endl;
	cout << f << endl;
}

int main()
{
	auto bindFun1 = bind(TestFun, placeholders::_1, 'A', 100.1);
	bindFun1(10);
	cout << "=================================" << endl;
	auto bindFun2 = bind(TestFun, placeholders::_2, placeholders::_3, placeholders::_1);
	bindFun2(100.1, 30, 'C');
}

输出结果
std::placeholders是一个占位符。当使用bind生成一个新的可调用对象时,std::placeholders表示新的可调用对象的第 几个参数和原函数的第几个参数进行匹配。

对于这个代码片段而言,bind函数用于绑定TestFun函数,所以bind的第一个参数为TestFun。后面的三个参数依次对应TestFun的三个参数。除了这个以外,以bindFun2为例,第一个参数placeholders::_2代表调用到bindFun2的时候,它的第二个参数和TestFun的第一个参数匹配,以此类推。以bindFunc1为例,除了TestFun外的第三个参数为100.1,即调用bindFun1的时候,第三个参数缺省地为100.1。

借助std::bind绑定类成员函数

在C++11标准中,std::function并不能直接调用成员函数,因此需要借助std::bind。参考博客std::bind

#include <iostream>
#include <string>
#include <functional>
using namespace std;

class Calculate
{
public:
	void add(int n,float f)
	{
		cout << n+f << endl;
	}
};

int main()
{
	Calculate c;
	typedef function<void(int, float)> Fun_Add;		//定义函数指针数据类型
	Fun_Add addFun = bind(&Calculate::add, &c, placeholders::_1, placeholders::_2);	//为函数指针变量赋值
	addFun(1, 3.14);
}

这里仍然是typedef定义了函数指针数据类型。不过,为函数指针数据addFun赋值的时候,用到了bind函数,从而将类Calculate的c对象的成员函数add,赋值给了函数指针变量addFun。此处bind的使用格式应为
bind(&[类名]::[成员函数名],[对象地址],[参数列表])

以实际项目为例

在实际工程应用中,可能会遇到这样的回调函数使用情况。下层的LowerClass负责数据处理,每处理一批数据会交给上层UpperClass使用。因为处理数据的时间不确定,且希望能够尽可能快地交付,就用到了回调函数机制。

#include <functional>
#include <Windows.h>
class LowerClass
{
public:
	LowerClass(){
		this->m_ProcessPerDataFun = nullptr;
	}
	~LowerClass(){}
	typedef std::function<void(int)> Fun_ProcessPerDataEvent;	//定义指针函数数据类型,处理每批次数据后的操作
	void BindProcessPerDataEvent(Fun_ProcessPerDataEvent eventFun)	//注册接收数据回调函数
	{
		this->m_ProcessPerDataFun = eventFun;
	}
	void Process()	//数据处理函数,实际使用中可以为它创建一个线程
	{
		int n = 0;
		while (true)
		{
			Sleep(100);	//模拟数据处理过程
			n++;
			if (m_ProcessPerDataFun != nullptr)
				m_ProcessPerDataFun(n);
		}
	}
private:
	Fun_ProcessPerDataEvent m_ProcessPerDataFun;	//传递参数
};
//UpperClass.h
#include "LowerClass.h"
#include <iostream>
class UpperClass
{
public:
	UpperClass()
	{
		m_pLower = new LowerClass();
		m_pLower->BindProcessPerDataEvent(std::bind(&UpperClass::printNum,this,std::placeholders::_1));
	}
	~UpperClass() {}
	LowerClass *m_pLower;
private:
	void printNum(int n)
	{
		std::cout << n << std::endl;
	}
};
//main.cpp
#include <iostream>
#include <Windows.h>
#include <functional>
#include "UpperClass.h"

int main()
{
	UpperClass *up = new UpperClass();
	up->m_pLower->Process();
	return 0;
}

运行结果
下层的数据处理类LowerClass里面定义了一个回调函数成员变量Fun_ProcessPerDataEvent。靠上层UpperClass调用BindProcessPerDataEvent,为这个回调函数指针变量赋值,从而告诉他需要执行什么功能。而数据处理类本身并不关心这个函数的功能,只是在处理完每一批数据后调用这个回调函数而已。这样就能够实现实时传递数据处理结果,并保证良好的封装性。

参考链接:
https://www.cnblogs.com/danshui/archive/2012/01/02/2310114.html
https://blog.csdn.net/sinat_38183777/article/details/83958887
https://zhuanlan.zhihu.com/p/83943973
https://blog.csdn.net/u013654125/article/details/100140328

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的回调函数是指将一个函数作为参数传递给另一个函数,以便在需要的时候调用该函数回调函数通常用于事件处理或异步编程中。 以下是一个简单的回调函数示例: ```c++ #include <iostream> void printResult(int result) { std::cout << "Result: " << result << std::endl; } void calculate(int x, int y, void (*callback)(int)) { int result = x + y; callback(result); } int main() { calculate(5, 7, printResult); return 0; } ``` 在上面的示例中,`calculate()`函数接受两个整数和一个函数指针作为参数。它计算这两个整数的和,并将结果传递给回调函数。`printResult()`函数被传递给`calculate()`函数作为回调函数。当`calculate()`函数计算出结果后,它调用回调函数`printResult()`来打印结果。 此外,C++11引入了`std::function`和`std::bind`,它们可以更方便地使用回调函数。例如: ```c++ #include <iostream> #include <functional> void printResult(int result) { std::cout << "Result: " << result << std::endl; } void calculate(int x, int y, std::function<void(int)> callback) { int result = x + y; callback(result); } int main() { auto f = std::bind(printResult, std::placeholders::_1); calculate(5, 7, f); return 0; } ``` 在这个示例中,`calculate()`函数接受两个整数和一个`std::function`对象作为参数。`std::function`对象包装回调函数`printResult()`,并将其传递给`calculate()`函数。`std::bind`函数用于将回调函数绑定到要传递的参数上。最后,`f`对象被传递给`calculate()`函数作为回调函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值