C++ std::function<void(int)> 和 std::function<void()> 作为函数参数的注意事项
前言
std::function 作為標準庫提供的函數指針,使用起來還是比較方便的,不過在使用過程中有一些需要注意的細節,這里做一個簡單的記錄。
基本使用
- 頭文件:
#include <functional> - 語法:
std::function<return_type(args_type)>
其中return_type 是函數指針的返回值類型,像上面案例中#include <iostream> #include <functional> using namespace std; void func(int i, int g) {int count = 10;while (count > 0) {cout << "func: " << i << " " << g<< endl;sleep(1);} }int main() {std::function<void(int,int)> job = func;job(10,10);return 0; }func函數的void類型。
其中args_type 是函數指針的參數類型,有多個函數參數,就可以有多個數據類型。
函數指針作為參數 需要注意的事項
-
如果直接使用一個已經存在的函數來進行傳參數,則需要聲明調用者函數參數的
std::function為const類型。
具體也就是類似 我們使用"dfafasd" 初始化一個void test_string(std::string& res)引用類型的字符串參數。這個時候因為是引用傳遞,而傳遞的時候卻沒有用變量,而是使用了一個常量,則需要保證這個函數的聲明參數中有一個const ,才能將常量數據的地址正確得放在常量區域。即 正確的聲明應該如void test_string(const std::string& res)同理,std::function在使用一個已經存在的函數初始化的時候類似。如下代碼是正確的:
void stl_func(const std::function<void(int, int)>& job, int num, int g) {job(num, g); } void func(int i, int g) {int count = 10;while (count > 0) {cout << "func: " << i << " " << g<< endl;sleep(1);} }int main() {stl_func(func,10,1);return 0; }如果這個時候去掉了
stl_func函數參數中的 const 聲明,則會報如下錯誤:candidate function not viable: no know conversion from 'void()' to 'std::function<void(int,int)> &' for 1'st argument. -
使用一個函數指針變量 來進行參數傳遞,則不需要調用者函數參數的
std::function為const。
還是如上代碼,修改之后:void stl_func(std::function<void(int, int)>& job, int num, int g) {job(num, g); } void func(int i, int g) {int count = 10;while (count > 0) {cout << "func: " << i << " " << g<< endl;sleep(1);} }int main() {std::function<void(int, int)> job = func;// 使用函數指針 變量進行傳遞就沒有問題stl_func(job, 10, 10);return 0; } -
在類的成員函數之間 將 std::function 作為參數傳遞時需要注意 如下使用過程:
#include <iostream> #include <functional>using namespace std; void stl_func_bak(std::function<void()>& job) {job(); }class Cb {public:static void cb_func() {while(1) {cout << "cb_func: " << 10 << endl;usleep(100000);}}void stl_cb_func() {// 函數成員作為傳遞的參數需要確保編譯期間就能夠分配好函數內存// 函數棧需要在編譯期間獲得內存,所以需要聲明 cb_func 成員函數 為 staticstl_func_bak(Cb::cb_func);} };int main() {Cb* cb = new Cb();cb->stl_cb_func();return 0; }
歡迎大家補充使用過程中遇到的問題
總結
以上是生活随笔為你收集整理的C++ std::function<void(int)> 和 std::function<void()> 作为函数参数的注意事项的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我爱爱爱爱你是哪首歌啊?
- 下一篇: 求一个胖的个性签名