zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++中的函数指针

C++ 函数指针
2023-09-11 14:19:51 时间


1.函数指针

typedef unsigned int bool;

typedef bool(*pCopySDMMC2Mem)(int, unsigned int, unsigned short, unsigned int*, bool);

typedef void (*pBL2Type)(void);

pCopySDMMC2Mem p1=(pCopySDMMC2Mem)0xD0037F98;

pBL2Type p2 = (pBL2Type)0x23E00000;


2.简化函数指针类型声明

typedef bool Func(int a,int b);  //函数类型
typedef decltype(add) Func;  //函数类型
using Func=int(int,int);  //使用类型别名简化,函数类型
typedef bool (*Func)(int a,int b);  //函数指针类型
typedef decltype(add) *Func;  //函数指针类型
using Func=int(*)(int,int);  //使用类型别名简化,函数类型


3.指向对象成员函数的指针

// 
std::string NewFileCommand::print()
{
  std::cout << " NewFileCommand::print " << std::endl;
  return std::string(" print result ");
}
//


// 参考:C++高级编程 第4版
// 函数指针别名
using Print_ptr = std::string (NewFileCommand::*)();
Print_ptr  print_ptr = &NewFileCommand::print;
std::string result1 = (this->*print_ptr)();

// 简化函数指针类型定义
// std::string (NewFileCommand::*print_method_ptr)() = &NewFileCommand::print;
auto print_method_ptr = &NewFileCommand::print;
std::string result2 = (this->*print_method_ptr)();


// 函数对象,需要应用#include <functional>
auto fun1 = std::mem_fn(&NewFileCommand::print);
std::cout << fun1(this) << std::endl;



//

4.对象成员函数的适配/代理

需要应用#include <functional>
绑定器: std::bind,
std::string NewFileCommand::network(const std::string &url)
{

......
}

std::packaged_task<std::string (const std::string &)> task(std::bind(&NewFileCommand::network, this, std::placeholders::_1));


绑定参数类型转换:std::ref, std::cref 分别用于绑定引用或const引用。
void increment(int &value) {
  ++value;
}

int index =0;
auto incr = std::bind(increment, ref(index));
incr();

//

 

当形参为

typedef std::function<restult_type()> RequestCallback;

void setRequestFunction(RequestCallback &&requestCallback);

实参可以为 函数指针,函数对象,对象成员函数(通过std::bind传入this指针)

所以当定义回调时,最好定义为std::function<>类型


------------------------------