简体   繁体   中英

Trouble compiling a simple C++0x program with lambdas

I am trying to run a simple lambda example.

// 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 ?

Standard library features live in the std namespace.

It's also interesting that your copy/paste is clearly fake; you wrote "lamdas.cpp" then compiled "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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