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

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

ztj100 2025-01-14 19:12 16 浏览 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;
}

相关推荐

30天学会Python编程:16. Python常用标准库使用教程

16.1collections模块16.1.1高级数据结构16.1.2示例...

强烈推荐!Python 这个宝藏库 re 正则匹配

Python的re模块(RegularExpression正则表达式)提供各种正则表达式的匹配操作。...

Python爬虫中正则表达式的用法,只讲如何应用,不讲原理

Python爬虫:正则的用法(非原理)。大家好,这节课给大家讲正则的实际用法,不讲原理,通俗易懂的讲如何用正则抓取内容。·导入re库,这里是需要从html这段字符串中提取出中间的那几个文字。实例一个对...

Python数据分析实战-正则提取文本的URL网址和邮箱(源码和效果)

实现功能:Python数据分析实战-利用正则表达式提取文本中的URL网址和邮箱...

python爬虫教程之爬取当当网 Top 500 本五星好评书籍

我们使用requests和re来写一个爬虫作为一个爱看书的你(说的跟真的似的)怎么能发现好书呢?所以我们爬取当当网的前500本好五星评书籍怎么样?ok接下来就是学习python的正确姿...

深入理解re模块:Python中的正则表达式神器解析

在Python中,"re"是一个强大的模块,用于处理正则表达式(regularexpressions)。正则表达式是一种强大的文本模式匹配工具,用于在字符串中查找、替换或提取特定模式...

如何使用正则表达式和 Python 匹配不以模式开头的字符串

需要在Python中使用正则表达式来匹配不以给定模式开头的字符串吗?如果是这样,你可以使用下面的语法来查找所有的字符串,除了那些不以https开始的字符串。r"^(?!https).*&...

先Mark后用!8分钟读懂 Python 性能优化

从本文总结了Python开发时,遇到的性能优化问题的定位和解决。概述:性能优化的原则——优化需要优化的部分。性能优化的一般步骤:首先,让你的程序跑起来结果一切正常。然后,运行这个结果正常的代码,看看它...

Python“三步”即可爬取,毋庸置疑

声明:本实例仅供学习,切忌遵守robots协议,请不要使用多线程等方式频繁访问网站。#第一步导入模块importreimportrequests#第二步获取你想爬取的网页地址,发送请求,获取网页内...

简单学Python——re库(正则表达式)2(split、findall、和sub)

1、split():分割字符串,返回列表语法:re.split('分隔符','目标字符串')例如:importrere.split(',','...

Lavazza拉瓦萨再度牵手上海大师赛

阅读此文前,麻烦您点击一下“关注”,方便您进行讨论和分享。Lavazza拉瓦萨再度牵手上海大师赛标题:2024上海大师赛:网球与咖啡的浪漫邂逅在2024年的上海劳力士大师赛上,拉瓦萨咖啡再次成为官...

ArkUI-X构建Android平台AAR及使用

本教程主要讲述如何利用ArkUI-XSDK完成AndroidAAR开发,实现基于ArkTS的声明式开发范式在android平台显示。包括:1.跨平台Library工程开发介绍...

Deepseek写歌详细教程(怎样用deepseek写歌功能)

以下为结合DeepSeek及相关工具实现AI写歌的详细教程,涵盖作词、作曲、演唱全流程:一、核心流程三步法1.AI生成歌词-打开DeepSeek(网页/APP/API),使用结构化提示词生成歌词:...

“AI说唱解说影视”走红,“零基础入行”靠谱吗?本报记者实测

“手里翻找冻鱼,精心的布局;老漠却不言语,脸上带笑意……”《狂飙》剧情被写成歌词,再配上“科目三”背景音乐的演唱,这段1分钟30秒的视频受到了无数网友的点赞。最近一段时间随着AI技术的发展,说唱解说影...

AI音乐制作神器揭秘!3款工具让你秒变高手

在音乐创作的领域里,每个人都有一颗想要成为大师的心。但是面对复杂的乐理知识和繁复的制作过程,许多人的热情被一点点消磨。...

取消回复欢迎 发表评论: