從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。
你聲明你的'func'沒有參數。 – melpomene
'void()'是不接受任何東西的函數的簽名,不返回任何內容。 'print'的簽名是什麼?另外,不要試圖通過試驗和錯誤來學習C++。這隻會對你自己造成傷害。我強烈建議你看看[建議的閱讀材料](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – StoryTeller
@StoryTeller謝謝你回答我的問題。我一直在學習C++大約一個月(既觀看[夢幻般的YouTube系列](https://www.youtube.com/watch?v=18c3MTX0PK0&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)以及獲得輔導)。可能試圖比我的能力更快地學習 - 這是一個相當令人沮喪的不能實現使用其他語言獲得的技術。 – Greg