C++ std::function 用法與範例

本篇介紹 C++ 的 std::function 的用法教學,並提供一些入門常用的範例程式碼。

需要引入的標頭檔<functional>

在實務上最常用到 std::function 的情形就是使用 callback 回調函式的時候,

使用 std::function 取代傳統的 function pointer

使用 std::function 取代傳統的 function pointer 優點有幾個,

  • 可讀性佳
  • 可接受 lambda 函式

讓我們先來看看一段使用 function pointer 的範例,

function-pointer-callback.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// g++ function-pointer-callback.cpp -o a.out
#include <iostream>
#include <string>
using namespace std;

void keyevent(int keycode, int status) {
cout << "keycode = " << keycode << " status = " << status << endl;
}

int main() {
void (*callback_keyevent)(int, int) = NULL;
callback_keyevent = keyevent;

if (callback_keyevent)
callback_keyevent(1, 0);

return 0;
}

改成 std::function 後變成這樣

std-function-callback.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// g++ std-function-callback.cpp -o a.out -std=c++11
#include <iostream>
#include <string>
#include <functional>
using namespace std;

void keyevent(int keycode, int status) {
cout << "keycode = " << keycode << " status = " << status << endl;
}

int main() {
std::function<void(int, int)> callback_keyevent = nullptr;
callback_keyevent = keyevent;

if (callback_keyevent)
callback_keyevent(1, 0);

return 0;
}

參考
[1] std::function - cppreference.com
https://en.cppreference.com/w/cpp/utility/functional/function
[2] function::function - C++ Reference
http://www.cplusplus.com/reference/functional/function/function/
[3] C++11 std::function的用法 - 滴酱的个人空间 - OSCHINA
https://my.oschina.net/u/2274890/blog/499159
[4] C++11 std::function用法-码农场
https://www.hankcs.com/program/cpp/c11-std-function-usage.html
[5] Cocos2d-x 的 onKeyPressed 與 onKeyReleased
https://github.com/cocos2d/cocos2d-x/blob/e3438ed3fd10a304b7ca2cd3dad9b29fead818d2/cocos/base/CCEventListenerKeyboard.h
https://github.com/cocos2d/cocos2d-x/blob/e3438ed3fd10a304b7ca2cd3dad9b29fead818d2/cocos/base/CCEventListenerKeyboard.cpp
https://github.com/cocos2d/cocos2d-x/blob/e3438ed3fd10a304b7ca2cd3dad9b29fead818d2/tests/performance-tests/Classes/tests/PerformanceEventDispatcherTest.cpp
cocos2d-x 在 PerformanceEventDispatcherTest.cpp 的 KeyboardEventDispatchingPerfTest::generateTestFunctions 使用 onKeyPressed 接收一個 lambda 函式
[6] 邁向王者的旅途: 簡介 std::function (C++11 後的新功能)
https://shininglionking.blogspot.com/2017/01/stdfunction-c11.html
[7] Should I use std::function or a function pointer in C++? - Stack Overflow
https://stackoverflow.com/questions/25848690/should-i-use-stdfunction-or-a-function-pointer-in-c
這篇討論提到應該盡量使用 std::function 來取代 function pointer,除非有什麼其他特殊原因
[8] 在 C++ 裡傳遞、儲存函式 Part 3:Function Object in TR1 – Heresy’s Space
https://kheresy.wordpress.com/2010/11/12/function_object_tr1/

其它相關文章推薦
C/C++ 新手入門教學懶人包
std::thread 用法與範例
C++ std::sort 排序用法與範例完整介紹
std::queue 用法與範例
C++ virtual 的兩種用法
C/C++ 判斷檔案是否存在
C++ 設計模式 - 單例模式 Singleton Pattern
C/C++ call by value傳值, call by pointer傳址, call by reference傳參考 的差別