一 定義
頭檔案<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來完成。