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