0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

C++ function技术的实现与具体运用

Linux爱好者 来源:xdesk 作者:xdesk 2021-01-20 09:23 次阅读

【导读】:本文主要讲解C++ function技术的实现与具体运用。

std::function是一个函数对象的包装器,std::function的实例可以存储,复制和调用任何可调用的目标,包括:

函数。

lamada表达式。

绑定表达式或其他函数对象。

指向成员函数和指向数据成员的指针。

当std::function对象没有初始化任何实际的可调用元素,调用std::function对象将抛出std::bad_function_call异常。

本文我们来谈一下std::function的实现原理。

1. std::function简介

在讨论其原理的时候,我们来熟悉一下这个东西是怎么使用的,C++标准库详细说明了这个的基本使用http://www.cplusplus.com/reference/functional/function/.

这里我们大概总结一下。

1.1 Member types

result_type 返回类型
argument_type 如果函数对象只有一个参数,那么这个代表参数类型。
first_argument_type 如果函数对象有两个个参数,那么这个代表第一个参数类型。
second_argument_type 如果函数对象有两个个参数,那么这个代表第二个参数类型。
成员类型 说明

1.2 Member functions

constructor 构造函数:constructs a new std::function instance
destructor 析构函数:destroys a std::function instance
operator= 给定义的function对象赋值
operator bool 检查定义的function对象是否包含一个有效的对象
operator() 调用一个对象
成员函数声明 说明

1.3 基本使用

#include #include intfun(inta,intb,intc,intd) { std::cout<< a << std::endl;  std::cout << b << std::endl;  std::cout << c << std::endl;  std::cout << d << std::endl;  return 0; } class CCaller { public:  int operator()(int a, int b, int c, int d)  {   std::cout << a << std::endl;   std::cout << b << std::endl;   std::cout << c << std::endl;   std::cout << d << std::endl;   return 0;  } }; int main() {  CCaller Caller;  std::functionf; f=[](inta,intb,intc,intd)->int { std::cout<< a << std::endl;   std::cout << b << std::endl;   std::cout << c << std::endl;   std::cout << d << std::endl;   return 0;  };  f(1, 2, 3, 4);  f = Caller;  f(10, 20, 30, 40);  f = fun;  f(100, 200, 300, 400);     return 0; }

从上面我们可以发现,std::function可以表示函数,lamada,可调用类对象。

2. std::function实现

在标准库中STL设计为如下:

template struct_Arg_types {//provideargument_type,etc.(sometimes) }; template struct_Arg_types<_Ty1> {//provideargument_type,etc.(sometimes) typedef_Ty1argument_type; }; template struct_Arg_types<_Ty1, _Ty2> {//provideargument_type,etc.(sometimes) typedef_Ty1first_argument_type; typedef_Ty2second_argument_type; }; template class_Func_class :public_Arg_types<_Types...> {//implementfunctiontemplate public: typedef_Retresult_type; typedef_Func_class<_Ret, _Types...>_Myt; typedef_Func_base<_Ret, _Types...>_Ptrt; private: bool_Local()const_NOEXCEPT {//testforlocallystoredcopyofobject return(_Getimpl()==_Getspace()); } union_Storage {//storageforsmallobjects(basic_stringissmall) max_align_t_Dummy1;//formaximumalignment char_Dummy2[_Space_size];//topermitaliasing _Ptrt*_Ptrs[_Num_ptrs];//_Ptrs[_Num_ptrs-1]isreserved }; _Storage_Mystorage; }; template struct_Get_function_impl<_Ret CALL_OPT (_Types...)> {/*determinetypefromargumentlist*/ typedef_Func_class<_Ret, _Types...>type; }; template classfunction :public_Get_function_impl<_Fty>::type {//wrapperforcallableobjects public: typedeffunction<_Fty>_Myt; };

上面的std::function继承关系比较简单,主要使用

union_Storage { //storageforsmallobjects(basic_stringissmall) max_align_t_Dummy1;//formaximumalignment char_Dummy2[_Space_size];//topermitaliasing _Ptrt*_Ptrs[_Num_ptrs];//_Ptrs[_Num_ptrs-1]isreserved };

这个来存储我们设置的可调用对象,我们从std::function的使用过程看一下整个原理。

2.1 函数对象赋值

我们使用的时候一般使用f = Caller;来设置函数对象,我们看下这个的实现过程。

template _Myt&operator=(reference_wrapper<_Fx>_Func)_NOEXCEPT { //assignwrapperholdingreference_wrappertofunctionobject this->_Tidy(); this->_Reset(_Func); return(*this); }

我们看this->_Reset(_Func)这个函数,因为这个才是设置函数可调用对象的东西。

void_Set(_Ptrt*_Ptr)_NOEXCEPT {//storepointertoobject _Mystorage._Ptrs[_Num_ptrs-1]=_Ptr; } void_Reset_impl(_Fx&&_Val,const_Alloc&_Ax, _Myimpl*,_Alimpl&_Al,false_type) {//storecopyof_Valwithallocator,small(locallystored) _Myimpl*_Ptr=static_cast<_Myimpl *>(_Getspace()); _Al.construct(_Ptr,_STDforward<_Fx>(_Val),_Ax); _Set(_Ptr); } template void_Reset_alloc(_Fx&&_Val,const_Alloc&_Ax) {//storecopyof_Valwithallocator if(!_Test_callable(_Val)) {//nullmemberpointer/functionpointer/std::function return;//alreadyempty } typedeftypenamedecay<_Fx>::type_Decayed; typedef_Func_impl<_Decayed, _Alloc, _Ret, _Types...>_Myimpl; _Myimpl*_Ptr=0; typedef_Wrap_alloc<_Alloc>_Alimpl0; typedeftypename_Alimpl0::templaterebind<_Myimpl>::other_Alimpl; _Alimpl_Al(_Ax); _Reset_impl(_STDforward<_Fx>(_Val),_Ax, _Ptr,_Al,_Is_large<_Myimpl>()); } template void_Reset(_Fx&&_Val) { //storecopyof_Val _Reset_alloc(_STDforward<_Fx>(_Val),allocator()); }

这个代码的主要意思就是创建一个_Func_impl<_Decayed, _Alloc, _Ret, _Types...>指针,然后赋值_Mystorage._Ptrs[_Num_ptrs - 1] = _Ptr;。

设置之后,我们看下调用操作怎么完成。

2.2 operator() 的实现

调用操作主要是通过operator()来实现的,我们看下这个的实现过程。

_Ptrt*_Getimpl()const_NOEXCEPT {//getpointertoobject return(_Mystorage._Ptrs[_Num_ptrs-1]); } _Retoperator()(_Types..._Args)const {//callthroughstoredobject if(_Empty()) _Xbad_function_call(); return(_Getimpl()->_Do_call(_STDforward<_Types>(_Args)...)); }

因此,我们是通过_Func_impl<_Decayed, _Alloc, _Ret, _Types...>转发了调用操作_Do_call

2.3 _Func_impl的实现

class_Func_impl :public_Func_base<_Rx, _Types...> {//derivedclassforspecificimplementationtypes public: typedef_Func_impl<_Callable, _Alloc, _Rx, _Types...>_Myt; typedef_Func_base<_Rx, _Types...>_Mybase; typedef_Wrap_alloc<_Alloc>_Myalty0; typedeftypename_Myalty0::templaterebind<_Myt>::other_Myalty; typedefis_nothrow_move_constructible<_Callable>_Nothrow_move; virtual_Rx_Do_call(_Types&&..._Args) {//callwrappedfunction return(_Invoke_ret(_Forced<_Rx>(),_Callee(), _STDforward<_Types>(_Args)...)); } _Compressed_pair<_Alloc, _Callable>_Mypair; };

_Func_impl这个类通过_Do_call来转发函数对象的调用操作。

3. 总结

这里我们看下std::function的结构信息,如下:

330d8784-5788-11eb-8b86-12bb97331649.png

从这里我们发现_Storage大小为:

constint_Num_ptrs=6+16/sizeof(void*); constsize_t_Space_size=(_Num_ptrs-1)*sizeof(void*);

_Num_ptrs值为10。

如果我们赋值的对象有成员变量会是什么情况呢?例如如下:

classCCaller { public: intoperator()(inta,intb,intc,intd) { std::cout<< a << std::endl;   std::cout << b << std::endl;   std::cout << c << std::endl;   std::cout << d << std::endl;   return 0;  }  int a = 1;  int b = 10;  int c = 100; }; int main() {  CCaller Caller;  std::functionf; f=Caller; f(10,20,30,40); return0; }

内存结构如下:

333686e8-5788-11eb-8b86-12bb97331649.png

由此我们可以发现std::function是利用一个_Compressed_pair<_Alloc, _Callable> _Mypair;拷贝了元素的数据信息。

主要的初始化过程为:

emplate void_Reset_alloc(_Fx&&_Val,const_Alloc&_Ax) {//storecopyof_Valwithallocator if(!_Test_callable(_Val)) {//nullmemberpointer/functionpointer/std::function return;//alreadyempty } typedeftypenamedecay<_Fx>::type_Decayed; typedef_Func_impl<_Decayed, _Alloc, _Ret, _Types...>_Myimpl; _Myimpl*_Ptr=0; typedef_Wrap_alloc<_Alloc>_Alimpl0; typedeftypename_Alimpl0::templaterebind<_Myimpl>::other_Alimpl; _Alimpl_Al(_Ax); _Reset_impl(_STDforward<_Fx>(_Val),_Ax, _Ptr,_Al,_Is_large<_Myimpl>()); }

其中decay<_Fx>::type定义了_Compressed_pair<_Alloc, _Callable> _Mypair;中_Callable的类型,这个声明如下(也就是去掉引用和其他属性信息):

template structdecay {//determinesdecayedversionof_Ty typedeftypenameremove_reference<_Ty>::type_Ty1; typedeftypename_If::value, typenameremove_extent<_Ty1>::type*, typename_If::value, typenameadd_pointer<_Ty1>::type, typenameremove_cv<_Ty1>::type>::type>::typetype; };

至此,我们大致上完成了std::function的原理分析了,希望在后续的使用中,我们能够知道std::function在什么情况下可以使用,以及背后完成的事情。

责任编辑:lq

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 函数
    +关注

    关注

    3

    文章

    3864

    浏览量

    61304
  • C++
    C++
    +关注

    关注

    21

    文章

    2066

    浏览量

    72893
  • 初始化
    +关注

    关注

    0

    文章

    48

    浏览量

    11627

原文标题:C++ std::function 技术浅谈

文章出处:【微信号:LinuxHub,微信公众号:Linux爱好者】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    C/C++代码动态测试工具VectorCAST插桩功能演示#代码动态测试 #C++

    C++代码
    北汇信息POLELINK
    发布于 :2024年04月18日 11:57:45

    请问CubeIDE如何支持C++的开发?

    CubeIDE如何支持C++的开发。有没有一些例程。
    发表于 03-25 06:22

    verilog task和function区别

    verilog中的task和function都是用于实现模块中的可重复的功能,并且可以接收参数和返回结果。但是它们在编写和使用上有一些区别。下面将详细介绍task和function的区别。 语法结构
    的头像 发表于 02-22 15:53 240次阅读

    什么是C++虚函数? 应该怎么定义? 用途是什么?

    什么是C++虚函数? 应该怎么定义? 主要用途是什么?
    发表于 11-08 06:58

    高质量CC++编程指南

    林锐-高质量CC++编程指南电子档
    发表于 10-07 07:14

    【verilog每日一练】function的使用

    function实现a,b,c三个输入数据取最大值
    发表于 09-04 16:59

    Arm C/C++编译器22.1版开发人员和参考指南

    提供帮助您使用ARM®编译器Linux版的ARM®C/C++编译器组件的信息。 ARM®C/C++编译器是一款自动矢量化的Linux空间C
    发表于 08-11 07:46

    Arm C/C++编译器开发人员和参考指南

    提供帮助您使用Arm®编译器Linux版的Arm®C/C++编译器组件的信息。Arm®C/C++编译器是一款自动向量化的Linux空间C
    发表于 08-10 06:17

    如何为Arm编译Cc++代码

    编写CC++应用程序时,需要使用编译器工具链将其编译为机器代码。然后,您可以在基于Arm的处理器上运行此编译的可执行代码,或者使用模型对其进行模拟。 裸机编译编译器工具链包括以下组件: •将C
    发表于 08-02 17:28

    重点了解一下C++11 包装器function

    C++提供了多个包装器,它们主要是为了给其他编程接口提供更一致或更合适的接口。C++11提供了多个包装器,这里我们重点了解一下包装器function
    的头像 发表于 07-18 16:41 369次阅读

    一起探索C++的世界!

    C++
    YS YYDS
    发布于 :2023年07月07日 19:10:25

    嵌入式-C++函数的重载

    一、什么是函数的重载 两个以上的函数,具有相同的函数名,通过参数的类型和参数的个数不同。编译器自行匹配,自动确定调用哪一个函数 二、函数重载的作用 C++允许功能相近的函数在相同的作用域内以相同
    发表于 06-28 13:54

    如何为xtensa编译C++

    我想为 xtensa 编译简单的 C++ 代码,但我不能。 代码:全选#include \"ets_sys.h\" #include \"osapi.h\"
    发表于 06-09 07:02

    S32和PowerPc artitechure是否支持项目的C++实现

    我想为 PowerPc MPC577C 实现 C++ 源代码。我更喜欢 freeGCC 作为编译器。我在实施过程中遇到了问题。我选择 C++11 作为版本。我想知道 S32 和 Pow
    发表于 05-12 06:15

    function与invoke的区别

    std::function和std::invoke是两个不同的东西,功能也不同。std::function 是一个函数对象的封装器,可以用来封装任意类型的可调用对象,比如函数指针、lambda表达式等
    的头像 发表于 04-27 15:13 464次阅读