百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

C++11很吊的新特性!std::function

yuyutoo 2025-01-16 21:30 4 浏览 0 评论

std::function简介

std::function是一个函数包装器,该函数包装器模板能包装任何类型的可调用实体,如普通函数,函数对象,lamda表达式等。包装器可拷贝,移动等,并且包装器类型仅仅依赖于调用特征,而不依赖于可调用元素自身的类型。std::function是C++11的新特性,包含在头文件<functional>中。

一个std::function类型对象实例可以包装下列这几种可调用实体:函数、函数指针、成员函数、静态函数、lamda表达式和函数对象。std::function对象实例可被拷贝和移动,并且可以使用指定的调用特征来直接调用目标元素。当std::function对象实例未包含任何实际可调用实体时,调用该std::function对象实例将抛出std::bad_function_call异常。

std::function实战

std::function模板类声明

template<class _Rp, class ..._ArgTypes>
class _LIBCPP_TEMPLATE_VIS function<_Rp(_ArgTypes...)>
    : public __function::__maybe_derive_from_unary_function<_Rp(_ArgTypes...)>,
      public __function::__maybe_derive_from_binary_function<_Rp(_ArgTypes...)>
{ ... }

std::function模板类成员函数声明

typedef _Rp result_type;

    // construct/copy/destroy:
    _LIBCPP_INLINE_VISIBILITY
    function() _NOEXCEPT { }
    _LIBCPP_INLINE_VISIBILITY
    function(nullptr_t) _NOEXCEPT {}
    function(const function&);
    function(function&&) _NOEXCEPT;
    template<class _Fp, class = _EnableIfCallable<_Fp>>
    function(_Fp);

#if _LIBCPP_STD_VER <= 14
    template<class _Alloc>
      _LIBCPP_INLINE_VISIBILITY
      function(allocator_arg_t, const _Alloc&) _NOEXCEPT {}
    template<class _Alloc>
      _LIBCPP_INLINE_VISIBILITY
      function(allocator_arg_t, const _Alloc&, nullptr_t) _NOEXCEPT {}
    template<class _Alloc>
      function(allocator_arg_t, const _Alloc&, const function&);
    template<class _Alloc>
      function(allocator_arg_t, const _Alloc&, function&&);
    template<class _Fp, class _Alloc, class = _EnableIfCallable<_Fp>>
      function(allocator_arg_t, const _Alloc& __a, _Fp __f);
#endif

    function& operator=(const function&);
    function& operator=(function&&) _NOEXCEPT;
    function& operator=(nullptr_t) _NOEXCEPT;
    template<class _Fp, class = _EnableIfCallable<_Fp>>
    function& operator=(_Fp&&);

    ~function();

    // function modifiers:
    void swap(function&) _NOEXCEPT;

#if _LIBCPP_STD_VER <= 14
    template<class _Fp, class _Alloc>
      _LIBCPP_INLINE_VISIBILITY
      void assign(_Fp&& __f, const _Alloc& __a)
        {function(allocator_arg, __a, _VSTD::forward<_Fp>(__f)).swap(*this);}
#endif

    // function capacity:
    _LIBCPP_INLINE_VISIBILITY
    _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {
      return static_cast<bool>(__f_);
    }

    // deleted overloads close possible hole in the type system
    template<class _R2, class... _ArgTypes2>
      bool operator==(const function<_R2(_ArgTypes2...)>&) const = delete;
    template<class _R2, class... _ArgTypes2>
      bool operator!=(const function<_R2(_ArgTypes2...)>&) const = delete;
public:
    // function invocation:
    _Rp operator()(_ArgTypes...) const;

#ifndef _LIBCPP_NO_RTTI
    // function target access:
    const std::type_info& target_type() const _NOEXCEPT;
    template <typename _Tp> _Tp* target() _NOEXCEPT;
    template <typename _Tp> const _Tp* target() const _NOEXCEPT;
#endif  // _LIBCPP_NO_RTTI

从成员函数里我们知道std::function对象实例不允许进行==和!=比较操作,std::function模板类实例最终调用成员函数_Rp operator()(_ArgTypes...) const进而调用包装的调用实体。

1、std::function包装函数指针

定义一个std::function<int(int)>对象实例

std::function<int(int)> callback;

std::function对象实例包装函数指针

int (*fun_ptr)(int);

int fun1(int a){
    return a;
}

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    fun_ptr = fun1; //函数指针fun_ptr指向fun1函数
    callback = fun_ptr; //std::function对象包装函数指针
    std::cout << callback(10) << std::endl; //std::function对象实例调用包装的实体

    return 0;
}

2、std::function包装函数

int fun1(int a){
    return a;
}

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    callback = fun1; //std::function包装函数
    std::cout << callback(42) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

3、std::function包装模板函数

template<typename T>
T fun2(T a){
    return a + 2;
}

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    callback = fun2<int>; //std::function包装模板函数
    std::cout << callback(10) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

4、std::function包装函数对象

struct add{
    int operator()(int x){
        return x + 9;
    }
};

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    callback = add(); //std::function包装对象函数
    std::cout << callback(2) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

5、std::function包装lamda表达式

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    auto fun3 = [](int a) {return a * 2;}; //lamda表达式
    callback = fun3; //std::function包装lamda表达式
    std::cout << callback(9) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

6、std::function包装模板对象函数

template <typename T>
struct sub{
    T operator()(T a){
        return a - 8;
    }
};

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    callback = sub<int>(); //std::function包装模板对象函数
    std::cout << callback(2) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

7、std::function包装模板对象静态函数

template <typename T>
struct foo2{
    static T foo(T a){
        return a * 4;
    }
};

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    callback = foo2<int>::foo; //std::function包装模板对象静态函数
    std::cout << callback(3) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

8、std::function包装对象静态函数

struct foo1{
    static int foo(int a){
        return a * 3;
    }
};

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    callback = foo1::foo; //std::function包装对象静态函数
    std::cout << callback(5) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

9、std::function包装类成员函数

struct foo3{
    int foo(int a){
        return a * a;
    }
};

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    foo3 test_foo1;
    callback = std::bind(&foo3::foo, test_foo1, std::placeholders::_1); //std::function包装类成员函数
    std::cout << callback(9) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

这里我们用到了std::bind,C++11中std::bind函数的意义就如字面上的意思一样,用来绑定函数调用的某些参数。std::bind的思想其实是一种延迟计算的思想,将可调用对象保存起来,然后在需要的时候再调用。而且这种绑定是非常灵活的,不论是普通函数还是函数对象还是成员函数都可以绑定,而且其参数可以支持占位符。

这里的std::placeholders::_1是一个占位符,且绑定第一个参数,若可调用实体有2个形参,那么绑定第二个参数的占位符是std::placeholders::_2。

10、std::function包装模板类成员函数


template <typename T>
struct foo4{
    T foo(T a){
        return a * 6;
    }
};

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    foo4<int> test_foo2;
    callback = std::bind(&foo4<int>::foo, test_foo2, std::placeholders::_1); //std::function包装模板类成员函数
    std::cout << callback(7) << std::endl; //std::function对象实例调用包装的调用实体

    return 0;
}

11、std::function拷贝、移动

int main(int argc, char *argv[]){
    std::cout << "Hello world" << std::endl;

    std::function<int(int)> callback2 = callback; //拷贝赋值运算符
    std::cout << callback2(7) << std::endl;

    std::function<int(int)>&& callback3 = std::move(callback); //移动赋值运算符
    std::cout << callback3(7) << std::endl;
    std::cout << callback(7) << std::endl;

    std::function<int(int)> callback4(callback); //拷贝
    std::cout << callback4(7) << std::endl;

    return 0;
}

相关推荐

IntelliJ IDEA插件开发(java开发idea插件)

引言IntelliJIDEA是JetBrains公司开发的一款广受欢迎的集成开发环境(IDE)。它不仅支持Java等多种编程语言,还通过插件系统提供了强大的扩展能力。本分享旨在介绍如何使用Java开...

如何验证自己的idea或者如何产生idea?小编教你如何检索……

申请专利前首先要做的是检索查重,如果你的构思已经被别人申请过专利,那么就不符合专利“新颖性”的要求。因此,如果你有了idea之后如何验证自己的idea具备新颖性,或者如何产生idea呢?今天,小编带着...

idea激活码失效了,这样解决,稳定使用!

最近官网封控比较严格,正式版激活码是不是又掉线了?掉线请看这里,这里有一个解决的方法,就是让工具不联网就可以继续使用激活码了。激活码本来就叫离线激活码,现在要怎么使id工具不联网?·可以打开这里帮助,...

5分钟解决 IntelliJ IDEA 使用问题(免费激活至 2100 年)

直接进入正题!效果安装1.官网下载idea...

【中高级前端必看】- 结合代码实践,全面学习前端工程化

前言前端工程化,简而言之就是软件工程+前端,以自动化的形式呈现。就个人理解而言:前端工程化,从开发阶段到代码发布生产环境,包含了以下几个内容:开发构建测试部署...

Android绘制流程(android界面绘制)

Android绘制流程来源:极客头条MFC、WTL、DuiLib、QT、Skia、OpenGL。Android里面的画图分为2D和3D两种:2D是由Skia来实现的,3D部分是由OpenGL实现...

ExpandListView 的一种巧妙写法(g的另一种写法上下两个圈连起来怎么打)

ExpandListView大家估计也用的不少了,一般有需要展开的需求的时候,大家不约而同的都想到了它然后以前自己留过记录的一般都会找找以前自己的代码,没有记录习惯的就会百度、谷歌,这里吐槽一下,好几...

通过圆形载入View了解自定义View(圆形div怎么搞)

这是自定义View的第一篇文章,通过制作简单的自定义View来了解自定义View的流程。自定义View是Android学习和开发中必不可少的一部分。通过自定义View我们可以制作丰富绚丽的控件,自定...

鸿蒙开源第三方组件——自定义流式布局组件FlowLayout_ohos

前言基于安卓平台的自定义流式布局组件FlowLayout(https://blog.csdn.net/fzhhsa/article/details/103003019),实现了鸿蒙的功能化迁移和重构...

「经典总结」一个View,从无到有会走的三个流程,你知道吗?

...

手把手带你写FlowLayout(流式布局)

流式布局在android中主要应用在搜索记录和用户标签,下面是效果图首先我们分析流式布局的原理。其实就是当一个子view加上之前的子view的宽度超过了父容器的宽度的时候就换行。接下来我们手把手书写流...

Android View(android view使用mvvm架构)

AndroidUI界面架构每个Activity包含一个PhoneWindow对象,PhoneWindow设置DecorView为应用窗口的根视图,在里面就是TitleView和ContentView...

《教你步步为营掌握自定义View》一文读后感

今天读了简书作者[milter]的一篇文章《教你步步为营掌握自定义View》,大有裨益。作者以幽默风趣、通俗易懂的大白话一步步讲述了View的来龙去脉,甚是详尽,实属自定义View文集中的一篇非常优秀...

Android面试官:你究竟有多大的勇气,在简历上写了“精通”?

所周知,简历上“了解=听过名字;熟悉=知道是啥;熟练=用过;精通=做过东西”。最近在面试,我现在十分后悔在简历上写了“精通”二字…先给大家看看我简历上的技能清单:良好的java基础,熟悉掌握面向对象思...

iOS 视图---动画渲染机制探究(动画渲染用哪个软件最好)

腾讯Bugly特约作者:陈向文终端的开发,首当其冲的就是视图、动画的渲染,切换等等。用户使用App时最直接的体验就是这个界面好不好看,动画炫不炫,滑动流不流畅。UI就是App的门面,它的体验伴...

取消回复欢迎 发表评论: