1. 程式人生 > >C++11 std::function

C++11 std::function

一 定義

標頭檔案<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來完成。