简体   繁体   English

使用 lambda 编译简单的 C++0x 程序时遇到问题

[英]Trouble compiling a simple C++0x program with lambdas

I am trying to run a simple lambda example.我正在尝试运行一个简单的 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; };
}

I'm compiling it like this:我正在像这样编译它:

$ 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

How do I get it to compile with no errors?如何让它编译没有错误?

Did you mean std::function ?您是说std::function吗?

Standard library features live in the std namespace.标准库功能位于std命名空间中。

It's also interesting that your copy/paste is clearly fake;有趣的是,您的复制/粘贴显然是假的; you wrote "lamdas.cpp" then compiled "lambdas.cpp"!你写了“lamdas.cpp”然后编译了“lambdas.cpp”!

std::function<int (int, int)> f2 = [] (int x, int y) { return x + y; };

or, probably better或者,可能更好

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

It looks to me like you forgot -std=c++0x.在我看来,您忘记了 -std=c++0x。

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

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