错误:无法将'print'从'void(*)(int)'转换为'std :: function <void()>'

时间:2017-09-17 14:41:18

标签: c++ functional-programming

previous question开始,我被指向an answer。然而,答案涉及一个lambda函数,我试图通过一个正常的函数。

使用以下代码作为示例:

#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);
}

在CLion中返回以下错误。

/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 个答案:

答案 0 :(得分:1)

std::function<void()>表示&#34;函数返回void并且不带参数&#34;。您尝试传递的是print,这是一个返回void并且需要int&#34;的&#34;函数。类型不匹配。

forloop更改为:

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

另外,除非你有充分的理由,否则不要使用std::function传递lambdas。我建议阅读我关于这个主题的文章:"passing functions to functions"