C++11 std::function

版权声明: https://blog.csdn.net/luoshabugui/article/details/80969116

一 定义

头文件<funticonal>

先来看一段话

Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

 类模板 std::function 是通用多态函数封装器。可以存储普通函数、lambda表达式、类成员函数、类成员变量、仿函数等。

二 举例

#include <iostream>
#include <functional>

// 类
struct Demo
{
    void print(int a, int b)
    {
        std::cout << "Demo " << a << " " << b << " " << a_ << std::endl;
    };
    int a_ = 1;
};

// 普通函数
int add(int& a, int& b)
{
    a++;
    b++;
    std::cout << "add " << a << " " << b << std::endl;
    return a + b;
}

// 仿函数
struct PrintDemo
{
    void operator()(int i) const
    {
        std::cout << "PrintDemo " << i << std::endl;
    }
};

int main()
{
    using namespace std::placeholders;

    {
        int a = 1;
        int b = 2;
        // 1、存储普通函数
        std::function<int(int&, int&)> f = add; // 方式1
        // std::function<int(int&, int&)> f = std::bind(add, _1, _2); // 方式2

        f(a, b); // output: add 2 3
    }

    {
        // 2、绑定lambda
        std::function<void()> f = []()
		{
            std::cout << "hello" << std::endl;
        };
    }

    {
        Demo demo;
        // 3、存储成员函数
        std::function<void(Demo&, int, int)> f1 = &Demo::print; // 方式1
        // std::function<void(int, int)> f1 = std::bind(&Demo::print, &demo, _1, 10); // 方式2

        // 4、存储成员变量
        std::function<int(Demo&)> f2 = &Demo::a_; // 方式1
        // std::function<int(Demo&, int)> f2 = std::bind(&Demo::a_, _1); // 方式2

        f1(demo, 10, 20); // output: Demo 10 20 1
        std::cout << f2(demo); // output: 1
    }
    {
        // 5、存储仿函数
        std::function<void(int)> f = PrintDemo();
        f(100); // output: PrintDemo 100
    }
    system("pause");
    return 0;
}

三、注意点

1、std::function 和std::bind的头文件均是<functional>,查看 std::bind

2、std::function实现了一套类型消除机制,可以统一处理不同的函数对象类型。以前我们使用函数指针,现在我们可以使用std::function来完成。

猜你喜欢

转载自blog.csdn.net/luoshabugui/article/details/80969116
今日推荐