更新:
这些错误似乎来自Eclipse的代码分析器CODAN,这些错误出现在Problems视图中,并且在错误引用的行中以红色下划线。奇怪的是,构建项目成功地创建了可执行文件,并且生成没有在控制台中报告这些错误。我可以运行该可执行文件并获得预期的输出。
所以现在的问题是:如何让Eclipse的CODAN认识到使用std::function的lambda和函数指针不是错误?
原题:
在下面的C++代码中,它直接用g++编译得很好,但是在Eclipse中会导致错误。如何让我的Eclipse项目识别和允许在std::function中使用lambdas (或函数指针)
注意:更新请参见问题底部的编辑。
#include <functional>
#include <iostream>
void foo(int i) {
std::cout << i << std::endl;
}
void function_ptr(void (*bar)(int)) {
bar(1);
}
void function_std(std::function<void(int)> baz) {
baz(2);
}
int main() {
// these function calls are ok
function_ptr(&foo);
function_ptr([](int i) -> void {
foo(i);
});
// these function calls cause errors
function_std(&foo);
function_std([](int i) -> void {
foo(i);
});
// these assignments cause errors
std::function<void(int)> f1 = foo;
std::function<void(int)> f2 = [](int i) -> void {
foo(i);
};
f1(3);
f2(3);
return 0;
}在命令行上编译此代码按预期工作,并产生以下输出:
$ g++ src/LambdaFunctionParameterExample.cpp -o example
$ ./example
1
1
2
2
3
3但是,在Eclipse中,接受std::function作为参数的函数调用会产生以下错误:
Invalid arguments '
Candidates are:
void function_std(std::function<void (int)>)
'std::function变量赋值会产生以下错误:
Invalid arguments '
Candidates are:
function()
function(std::nullptr_t)
function(const std::function<void (int)> &)
function(std::function<void (int)> &&)
function(#10000)
'我在项目ISO C++17 (-std=c++17)属性中设置了->语言标准,-> C/C++构建-> GCC C++编译器->方言。(我假设设置此属性对于根据此<functional>访问文档报头是必要的。奇怪的是,指定语言级别(或不指定)并不会影响上述错误。而且,在使用g++直接构建时,没有必要指定语言级别。)
我正在使用macOS Catalina 10.15.5,gcc 10.2.0来自自制,和Eclipse版2020-09 (4.17.0)。
发布于 2020-12-09 03:58:18
此行为是EclipseCDT10.0版本的已知臭虫。
更新:
通过升级到Eclipse 10.1版本解决了这个问题:
https://download.eclipse.org/tools/cdt/builds/10.1/cdt-10.1.0-rc2/
修复步骤:
Help -> Install New Software... -> Work with:中输入上述URL并安装所有选项。Project -> C/C++ Index -> Rebuild。https://stackoverflow.com/questions/65207906
复制相似问题