C++ std::function C++ std::function详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++ std::function C++ std::function详解

物随心转   2021-10-11 我要评论
想了解C++ std::function详解的相关内容吗,物随心转在本文为您仔细讲解C++ std::function的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C++,std::function,C++,std::function详解,下面大家一起来学习吧。

一、介绍

std::function是函数模板类(是一个类)。包含在#include <functional> 中。以前没有这个类的时候,我们在想定义一个回调函数指针,非常的麻烦。我们通常这样的定义:

typedef  void(*ptr)(int,int)// 这里的ptr就是一个函数指针

而使用了std::function这个类的时候,我们可以这样使用,来替换函数指针。例如:

std::function<void(int ,int)> func;

std::function 的实例能存储、复制及调用任何可调用 (Callable) 目标——函数、 lambda 表达式、 bind 表达式或其他函数对象,还有指向成员函数指针和指向数据成员指针。

它也是对 C++ 中现有的可调用实体的一种类型安全的包裹(相对来说,函数指针的调用不是类型安全的)

二、实例

    #include <iostream>  
    #include <vector>  
    #include <list>  
    #include <map>  
    #include <set>  
    #include <string>  
    #include <algorithm>  
    #include <functional>  
    #include <memory>  
    using namespace std;  
    //声明一个模板  
    typedef std::function<int(int)> Functional;  
    //normal function  
    int TestFunc(int a)  
    {  
        return a;  
    }  
    //lambda expression  
    auto lambda = [](int a)->int{return a;};  
    //functor仿函数  
    class Functor  
    {  
    public:  
        int operator() (int a)  
        {  
            return a;  
        }  
    };  
    //类的成员函数和类的静态成员函数  
    class CTest  
    {  
    public:  
        int Func(int a)  
        {  
            return a;  
        }  
        static int SFunc(int a)  
        {  
            return a;  
        }  
    };  
    int main(int argc, char* argv[])  
    {  
        //封装普通函数  
        Functional obj = TestFunc;  
        int res = obj(0);  
        cout << "normal function : " << res << endl;  
        //封装lambda表达式  
        obj = lambda;  
        res = obj(1);  
        cout << "lambda expression : " << res << endl;  
        //封装仿函数  
        Functor functorObj;  
        obj = functorObj;  
        res = obj(2);  
        cout << "functor : " << res << endl;  
        //封装类的成员函数和static成员函数  
        CTest t;  
        obj = std::bind(&CTest::Func, &t, std::placeholders::_1);  
        res = obj(3);  
        cout << "member function : " << res << endl;  
        obj = CTest::SFunc;  
        res = obj(4);  
        cout << "static member function : " << res << endl;  
        return 0;  
    }  

运行结果

三、与std::bind的区别

可将std::bind函数看作一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。

std::bind将可调用对象与其参数一起进行绑定,绑定后的结果可以使用std::function保存。std::bind主要有以下两个作用:

  • 将可调用对象和其参数绑定成一个仿函数;
  • 只绑定部分参数,减少可调用对象传入的参数。
 double my_divide(double x, double y) { return x / y; };
 int main(int argc, char* argv[])
 {
	 auto fn_half = std::bind(my_divide, std::placeholders::_1, 2);
	 std::cout << fn_half(10) << '\n';                        // 输出为5
	 return 0;
}

参考:

C++ std::function的用法详解

C++11 中的std::function和std::bind - 简书

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们