天天看點

C++ std::function用法

參考自:https://www.cnblogs.com/lsgxeva/p/7787438.html

               https://www.cnblogs.com/nzbbody/p/3489573.html

在C++中,可調用實體主要包括函數,函數指針,函數引用,可以隐式轉換為函數指定的對象,或者實作了opetator()的對象(即C++98中的functor)。C++11中,新增加了一個std::function對象,std::function對象是對C++中現有的可調用實體的一種類型安全的包裹,比如:std::function<Layer*()>代表一個可調用對象,接收0個參數,傳回Layer*。

#include <iostream>
#include <map>
#include <functional>
using namespace std;
 
// 普通函數
int add(int i, int j) { return i + j; }
// lambda表達式
auto mod = [](int i, int j){return i % j; };
// 函數對象類
struct divide
{
    int operator() (int denominator, int divisor){
        return denominator / divisor;
    }
};


int main()
{

    map<char, function<int(int, int)>> binops = {
        { '+', add },
        { '-', minus<int>() },
        { '*', [](int i, int j){return i - j; } },
        { '/', divide() },
        { '%', mod },
    };
    cout << binops['+'](10, 5) << endl;
    cout << binops['-'](10, 5) << endl;
    cout << binops['*'](10, 5) << endl;
    cout << binops['/'](10, 5) << endl;
    cout << binops['%'](10, 5) << endl;
    return 0;
}
           

通過std::function的包裹,我們可以像傳遞普通的對象一樣來傳遞可調用實體,這樣就很好解決了類型安全的問題。

繼續閱讀