前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >回调函数在C++11中的另一种写法

回调函数在C++11中的另一种写法

作者头像
用户7886150
修改2021-02-11 18:18:07
2K0
修改2021-02-11 18:18:07
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: C++附近的int()

C++11之前写回调函数的时候,一般都是通过?

typedef void CALLBACK (*func)();

方式来声明具有某种参数类型、返回值类型的通用函数指针。上面例子声明了一个返回值是void,无参数的函数指针。

其中,返回值和参数可以使用 boost::any 或者 auto进行泛型指代。

C++11引入了

#include <functional>

包含2个函数std::function 和 std::bind。

其中std::function学名是可调用对象的包装器,作用和上面

typedef void CALLBACK (*func)();

差不多,都是指代一组具有参数个数和类型,以及返回值相同的函数。举例如下:

#include "stdafx.h"

#include<iostream>// std::cout

#include<functional>// std::function

void func(void)

{

? ? std::cout << __FUNCTION__ << std::endl;

}

class Foo

{

public:

? ? static int foo_func(int a)

? ? {

? ? ? ? std::cout << __FUNCTION__ << "(" << a << ") ->: ";

? ? ? ? return a;

? ? }

};

class Bar

{

public:

? ? int operator() (int a)

? ? {

? ? ? ? std::cout << __FUNCTION__ << "(" << a << ") ->: ";

? ? ? ? return a;

? ? }

};

int main()

{

? ? // 绑定普通函数

? ? std::function<void(void)> fr1 = func;

? ? fr1();

? ? // 绑定类的静态成员函数,需要加上类作用域符号

? ? std::function<int(int)> fr2 = Foo::foo_func;

? ? std::cout << fr2(100) << std::endl;

? ? // 绑定仿函数

? ? Bar bar;

? ? fr2 = bar;

? ? std::cout << fr2(200) << std::endl;

? ? return 0;

}

其中std::bind将可调用对象与实参进行绑定,绑定后可以赋值给std::function对象上,并且可以通过占位符std::placeholders::决定空位参数(即绑定时尚未赋值的参数)具体位置。举例如下:

#include "stdafx.h"

#include<iostream>// std::cout

#include<functional>// std::function

class A

{

public:

? ? int i_ = 0; // C++11允许非静态(non-static)数据成员在其声明处(在其所属类内部)进行初始化

? ? void output(int x, int y)

? ? {

? ? ? ? std::cout << x << "" << y << std::endl;

? ? }

};

int main()

{

? ? A a;

? ? // 绑定成员函数,保存为仿函数

? ? std::function<void(int, int)> fr = std::bind(&A::output, &a, std::placeholders::_1, std::placeholders::_2);

? ? // 调用成员函数

? ? fr(1, 2);

? ? // 绑定成员变量

? ? std::function<int&(void)> fr2 = std::bind(&A::i_, &a);

? ? fr2() = 100;// 对成员变量进行赋值

? ? std::cout << a.i_ << std::endl;

? ? return 0;

}

本文系转载,前往查看

如有侵权,请联系?cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系?cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com