c++11 - C++ lambda expressions - How does the compiler interpret them? -


i starter learning new features in c++ 11. reading lambdas in c++ primer (stanley lippman) , experimenting them.

i tried following pieces of code:

auto func() -> int (*) (){     //int c=0;     return []()-> int {return 0;}; }  int main(){     auto p = func(); } 

this code compiled fine. guess lambdas without captures generated normal functions compiler , can use normal function pointer them.

now changed code use captures:

auto func() -> int (*) (){     int c=0;     return [=]()-> int {return c;}; }  int main(){     auto p = func(); } 

but failed compile. got following compilation error while using g++:

main.cpp: in function ‘int (* func())()’: main.cpp:6:31: error: cannot convert ‘func()::__lambda0’ ‘int (*)()’ in return return [=]()-> int {return c;}; 

from error can understand not normal function generated , might class overloaded call-operator. or else?

my questions : how compiler handle lambdas internally? how should pass around lambdas use captures i.e. should return value func()? cant think of use case need use lambdas want understand more them. please help.

thanks.

all lambdas function objects implementation defined type called closure type operator() member. every lambda expression has it's own unique closure type, too.

lambdas without capture can converted function pointer. whether or not compiler generates normal function behind scenes internal detail , shouldn't matter you.

it's not possible return lambda that's defined inside function. there few things prevent - don't know name of type of lambda expression, can't use lambda expression inside decltype , said, 2 lambda expressions (even if lexically identical) have different types.

what can use std::function:

std::function<int()> func() {     int = 0;     return [=]()-> int {return i;}; } 

this way works captures, too.

or this:

auto f = []{ return 0; };  auto func() -> decltype(f) {     return f; } 

edit: upcoming c++1y standard (more specifically, return type deduction), however, allow this:

auto func() {     int = 42;     return [=]{ return i; };    } 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -