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

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

bigegpt 2024-09-17 12:25 9 浏览

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;
}

相关推荐

Go语言泛型-泛型约束与实践(go1.7泛型)

来源:械说在Go语言中,Go泛型-泛型约束与实践部分主要探讨如何定义和使用泛型约束(Constraints),以及如何在实际开发中利用泛型进行更灵活的编程。以下是详细内容:一、什么是泛型约束?**泛型...

golang总结(golang实战教程)

基础部分Go语言有哪些优势?1简单易学:语法简洁,减少了代码的冗余。高效并发:内置强大的goroutine和channel,使并发编程更加高效且易于管理。内存管理:拥有自动垃圾回收机制,减少内...

Go 官宣:新版 Protobuf API(go pro版本)

原文作者:JoeTsai,DamienNeil和HerbieOng原文链接:https://blog.golang.org/a-new-go-api-for-protocol-buffer...

Golang开发的一些注意事项(一)(golang入门项目)

1.channel关闭后读的问题当channel关闭之后再去读取它,虽然不会引发panic,但会直接得到零值,而且ok的值为false。packagemainimport"...

golang 托盘菜单应用及打开系统默认浏览器

之前看到一个应用,用go语言编写,说是某某程序的windows图形化客户端,体验一下发现只是一个托盘,然后托盘菜单的控制面板功能直接打开本地浏览器访问程序启动的webserver网页完成gui相关功...

golang标准库每日一库之 io/ioutil

一、核心函数概览函数作用描述替代方案(Go1.16+)ioutil.ReadFile(filename)一次性读取整个文件内容(返回[]byte)os.ReadFileioutil.WriteFi...

文件类型更改器——GoLang 中的 CLI 工具

我是如何为一项琐碎的工作任务创建一个简单的工具的,你也可以上周我开始玩GoLang,它是一种由Google制作的类C编译语言,非常轻量和快速,事实上它经常在Techempower的基准测...

Go (Golang) 中的 Channels 简介(golang channel长度和容量)

这篇文章重点介绍Channels(通道)在Go中的工作方式,以及如何在代码中使用它们。在Go中,Channels是一种编程结构,它允许我们在代码的不同部分之间移动数据,通常来自不同的goro...

Golang引入泛型:Go将Interface「」替换为“Any”

现在Go将拥有泛型:Go将Interface{}替换为“Any”,这是一个类型别名:typeany=interface{}这会引入了泛型作好准备,实际上,带有泛型的Go1.18Beta...

一文带你看懂Golang最新特性(golang2.0特性)

作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...

Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移

以下文章来源于GoOfficialBlog,作者GoOfficialBlogIntroductionagollo是Apollo的Golang客户端Apollo(阿波罗)是携程框架部门研...

Golang使用grpc详解(golang gcc)

gRPC是Google开源的一种高性能、跨语言的远程过程调用(RPC)框架,它使用ProtocolBuffers作为序列化工具,支持多种编程语言,如C++,Java,Python,Go等。gR...

Etcd服务注册与发现封装实现--golang

服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...

Golang:将日志以Json格式输出到Kafka

在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...

如何从 PHP 过渡到 Golang?(php转golang)

我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...