【问题标题】:Trouble compiling a simple C++0x program with lambdas使用 lambda 编译简单的 C++0x 程序时遇到问题
【发布时间】:2011-07-05 20:57:57
【问题描述】:

我正在尝试运行一个简单的 lambda 示例。

// lambda.cpp
#include <functional>
//#include <tr1/functional> 

int main()
{
   // Assign the same lambda expression to a function object.
   function<int (int, int)> f2 = [] (int x, int y) { return x + y; };
   //function<int (int, int)> f2 = [] (int x, int y) { return x + y; };
}

我是这样编译的:

$ g++ -std=c++0x -fpermissive lamdas.cpp
lambdas.cpp: In function ‘int main()’:    
lambdas.cpp:10: error: expected primary-expression before ‘=’ token
lambdas.cpp:10: error: expected primary-expression before ‘[’ token
lambdas.cpp:10: error: expected primary-expression before ‘]’ token
lambdas.cpp:10: error: expected primary-expression before ‘int’
lambdas.cpp:10: error: expected primary-expression before ‘int’
lambdas.cpp:10: error: expected ‘;’ before ‘{’ token

如何让它编译没有错误?

【问题讨论】:

  • 这是什么版本的 GNU c++?我从来没有看到过拼写正确的源文件名!
  • lambda 不是问题。你可以用其他东西替换它,你仍然会得到这些错误。
  • @Tomalak:我觉得它很有风格
  • @sehe:呵呵;他们在 C++0x 支持下引入了它,估计普通人写基本单词的能力会在新标准下一个小时后完全消失。
  • 老实说,我很惊讶编译器没有替换等效的 ISO 令牌 Λάμβδα(或 λ)以完全符合标准 :)

标签: c++ lambda c++11 compiler-errors


【解决方案1】:

你是说std::function吗?

标准库功能位于 std 命名空间中。

有趣的是,您的复制/粘贴显然是假的;你写了“lamdas.cpp”然后编译了“lambdas.cpp”!

【讨论】:

  • 他的源文件顶部还有lambda.cpp!!
  • @Marlon:肯定是犹豫不决的迹象!
  • 也被一些人称为“站立”命名空间:(
  • @sehe:我使用的是 GNU 4.4 版本的 c++。
  • @Sachin: Live example 的代码与 std:: 完美配合。
【解决方案2】:
std::function<int (int, int)> f2 = [] (int x, int y) { return x + y; };

或者,可能更好

auto f2 = [] (int x, int y) { return x + y; };

【讨论】:

  • 该死的;已经过了 5 分钟的窗口期,我本可以悄悄地偷走这个好主意。
  • 值得记住的是,这两种选择是完全不同的。
  • 不捕获任何内容的 Lambda 也可以隐式转换为函数指针。
  • @Tomalak:我尝试使用 std::function 但它似乎没有产生相同的编译错误。同意文件名错误和复制粘贴错误。
  • @Sachin:当然它不会产生同样的编译错误。 std:: 是您发布的解决方案
【解决方案3】:

在我看来你忘记了 -std=c++0x。

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多