繁体   English   中英

带有 std::function 的 lambda/函数指针导致错误

[英]lambda/function pointer with std::function causes error

更新:

这些错误似乎来自 Eclipse 的代码分析器 CODAN,它出现在 Problems 视图中,并且在错误所指的行上也带有红色下划线。 奇怪的是,构建项目成功创建了可执行文件,并且构建不会在控制台中报告这些错误。 我可以运行该可执行文件并获得预期的 output。

所以现在问题变成了:如何让 Eclipse 的 CODAN 识别这些使用 lambda 和 function 指针的std::function不是错误?

原始问题:

在下面的 C++ 代码中,它直接用g++编译良好,但在 Eclipse CDT 中导致错误。 如何让我的 Eclipse 项目识别并允许使用带有std::function的 lambdas(或 function 指针)?

注意:请参阅问题底部的编辑以获取更新

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

在命令行上编译此代码按预期工作,并生成以下 output:

$ g++ src/LambdaFunctionParameterExample.cpp -o example
$ ./example
1
1
2
2
3
3

但是在 Eclipse 中,接受std::function作为参数的 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)
'

我已在项目 -> 属性 -> C/C++ 构建 -> GCC ZF6F87C9FDCF8B3C3F07F93F1EE8712CZ Dia Compiler 中将语言标准设置为ISO C++17 (-std=c++17) (我假设根据本文档设置此属性是访问<functional> header 所必需的。奇怪的是,指定语言级别(或不指定)不会影响上述错误。并且,在构建时不需要指定语言级别直接用g++ 。)

我正在使用自制软件的 macOS Catalina 10.15.5、gcc 10.2.0 和 Eclipse CDT 版本 2020-09 (4.17.0)。

此行为是 Eclipse CDT 版本 10.0 的已知错误

更新:

此问题已通过升级到 Eclipse CDT 版本 10.1 得到修复:
https://download.eclipse.org/tools/cdt/builds/10.1/cdt-10.1.0-rc2/

修复步骤:

  1. Help --> Install New Software... --> Work with:中输入上述 URL 并安装所有选项。
  2. 重启 Eclipse。
  3. Select Project --> C/C++ Index --> Rebuild

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM