【问题标题】:error: could not convert ‘print’ from ‘void (*)(int)’ to ‘std::function<void()>’错误:无法将“print”从“void (*)(int)”转换为“std::function<void()>”
【发布时间】:2018-02-26 03:56:37
【问题描述】:

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++ 菜鸟。

【问题讨论】:

  • 您声明您的func 不接受任何参数。
  • void() 是一个函数的签名,它不接受任何内容,也不返回任何内容。 print 的签名是什么?另外,不要尝试通过反复试验来学习 C++。这只会对你自己造成伤害。我强烈建议您查看suggested reading material
  • @StoryTeller 感谢您回答我的两个问题。我已经学习 C++ 大约一个月了(观看fantastic youtube series 以及获得辅导)。可能试图比我的能力更快地学习 - 无法实施用其他语言获得的技术是相当令人沮丧的。
  • @Dave - 我真的无法评论视频教程的质量,但请记住,任何此类教程都没有经过同行评审。我给你的链接中的书籍由整个 C++ 社区在 SO 上推荐的。

标签: c++ functional-programming


【解决方案1】:

std::function&lt;void()&gt; 表示“返回void 且不带参数的函数”。您正尝试传递 print,这是一个“返回 void 并采用 int 的函数”。类型不匹配。

forloop 更改为:

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

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

【讨论】:

  • 感谢您的回答!并链接您的文章!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 2017-07-08
  • 2019-06-05
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多