备案 控制台
学习
实践
活动
专区
工具
TVP
写文章
专栏首页 bit哲学院 回调函数在C++11中的另一种写法
2 0

海报分享

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

参考链接: 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;

}

本文转载自: https://blog.csdn.net/jigetage/article/details/79724958?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161300848916780262543976%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=161300848916780262543976&biz_id=0&utm_medium=distribute.pc_search_result.none-t 复制
如有侵权,请联系 cloudcommunity@tencent.com 删除。