2017-09-17 65 views
0

previous question開始,我被指向an answer。然而,答案涉及一個lambda函數,我試圖通過一個正常的函數。錯誤:無法將'print'從'void(*)(int)'轉換爲'std :: function <void()>'

使用以下代碼作爲示例:

#include <iostream> 
#include <functional> 

void forloop(std::function<void()> func, int arg) { 
    func(arg); 
} 


void print(int number) { 
    std::cout << number << std::endl; 
} 


int main() { 
    int n = 5; 
    forloop(print, n); 
} 

在克利翁返回以下錯誤。

/home/dave/JetBrains/CLion/bin/cmake/bin/cmake --build /home/dave/CLionProjects/csv/cmake-build-debug --target csv -- -j 2 
Scanning dependencies of target csv 
[ 50%] Building CXX object CMakeFiles/csv.dir/main.cpp.o 
/home/dave/CLionProjects/csv/main.cpp: In function ‘void forloop(std::function<void()>, int)’: 
/home/dave/CLionProjects/csv/main.cpp:5:13: error: no match for call to ‘(std::function<void()>) (int&)’ 
    func(arg); 
      ^
In file included from /home/dave/CLionProjects/csv/main.cpp:2:0: 
/usr/include/c++/6/functional:2122:5: note: candidate: _Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = void; _ArgTypes = {}] 
    function<_Res(_ArgTypes...)>:: 
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
/usr/include/c++/6/functional:2122:5: note: candidate expects 0 arguments, 1 provided 
/home/dave/CLionProjects/csv/main.cpp: In function ‘int main()’: 
/home/dave/CLionProjects/csv/main.cpp:16:21: error: could not convert ‘print’ from ‘void (*)(int)’ to ‘std::function<void()>’ 
    forloop(print, n); 
        ^
CMakeFiles/csv.dir/build.make:62: recipe for target 'CMakeFiles/csv.dir/main.cpp.o' failed 
make[3]: *** [CMakeFiles/csv.dir/main.cpp.o] Error 1 
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/csv.dir/all' failed 
make[2]: *** [CMakeFiles/csv.dir/all] Error 2 
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/csv.dir/rule' failed 
make[1]: *** [CMakeFiles/csv.dir/rule] Error 2 
Makefile:118: recipe for target 'csv' failed 
make: *** [csv] Error 2 

道歉,如果這個問題看起來很愚蠢 - 我是一個C++的noob。

+1

你聲明你的'func'沒有參數。 – melpomene

+0

'void()'是不接受任何東西的函數的簽名,不返回任何內容。 'print'的簽名是什麼?另外,不要試圖通過試驗和錯誤來學習C++。這隻會對你自己造成傷害。我強烈建議你看看[建議的閱讀材料](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – StoryTeller

+0

@StoryTeller謝謝你回答我的問題。我一直在學習C++大約一個月(既觀看[夢幻般的YouTube系列](https://www.youtube.com/watch?v=18c3MTX0PK0&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)以及獲得輔導)。可能試圖比我的能力更快地學習 - 這是一個相當令人沮喪的不能實現使用其他語言獲得的技術。 – Greg

回答

1

std::function<void()>表示「返回void且不帶參數的函數」。您正試圖通過print,而這是一個「函數,返回void並採取int」。類型不匹配。

更改forloop到:

void forloop(std::function<void(int)> func, int arg) { /* ... */ } 

此外,不要使用std::function傳遞lambda表達式,除非你有一個很好的理由這樣做。我建議閱讀我關於這個問題的文章:"passing functions to functions"

+0

謝謝你的回答!並鏈接您的文章! – Greg

相關問題