Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures in C++

Tags:

c++

I've found myself in a strange place, mentally. In a C++ project, I long for closures.

Background. There's a Document-type class with a public Render method which spawns a deep call tree. There's some transient state that only makes sense during rendering. Right now it resides in the class like regular member variables. However, this is not satisfactory on some levels - this data only makes sense during a Render call, why store it all the time? Passing it around in arguments would be ugly - there are around 15 variables there. Passing around a structure would add a lot of "RenderState->..." in the lower-level methods.

So what do I want? I want the world, like we all do. Specifically, a set of variables that are:

  • available to some methods in a class (not all of them)
  • accessible by name alone (no pState->... stuff - so that refactoring is easy)
  • not copied around on every method call
  • only live during a method call and up its call tree (assuming trees grow up)
  • live on a stack

I know I can have some of those properties with C++ - but not all of them. Tell me I'm not turning weird.

Heck, in Pascal, of all places, nested functions give you all that...

So what is a good workaround to emulate closures in C++, getting as many of the above benefits as possible?

like image 999
Seva Alekseyev Avatar asked Nov 22 '25 04:11

Seva Alekseyev


1 Answers

Standard C++ since C++11 provides native lambda expressions and several compilers (VC10+ GCC and clang at least) implements it.

With GCC and Clang you can activate it with "--std=c++11" (or use a higher version of C++ if available). VC10 and later versions have it activated without need for flags.

By the way, you can also use boost::lambda (that is not perfect but works with C++03) also provide lambda in C++.

like image 144
Klaim Avatar answered Nov 23 '25 20:11

Klaim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!