Strange C++ syntax
Asked Answered
A

3

8

I have 8 years of coding experience, but I have never seen the operator [] passed as a parameter to the function definition.

For example, the following code (from an open source project):

bree::porder(m_root, [] (treenode* node) { delete node; }); 

Throughout my coding life, I have always defined [] as an operator overloader, not as a parameter.

So what does this new syntax signify?

I am using the compiler that comes with Visual Studio 2003. How can I change the above code so that it will compile in VS 2003?

Allseed answered 24/7, 2011 at 5:57 Comment(1)
A better read.Tremor
S
16

That is a c++ lambda you could replace the code with a function object of the same definition. The link shows two examples one using Functor and one using a lambda.

Soapstone answered 24/7, 2011 at 6:0 Comment(3)
So lambda functions come to c++... interesting. Can't say the syntax is particularly pretty or understandable thoughUtas
Yes, and they are (at least partially) supported by Visual Studio 2010. Good reason to upgrade compilers now; 2003 is getting pretty long in the tooth.Retiarius
@crasic: the syntax (the []'s at least) is mostly unavoidable, because you need to be able to specify whether to capture each variable by reference or value. (if everything was implicitly by reference, you'd run into all sorts of problems as your lambda holds references to objects that may have gone out of scope when you invoke the lambdaCurtiscurtiss
T
5

It looks like the C++0x syntax for an anonymous function

Truancy answered 24/7, 2011 at 6:1 Comment(1)
Both of the links are broken.Thomajan
S
5

As other answers have mentioned, its' a brand new syntax to support C++0x lambas. It is not supported in any version of Visual Studio prior to VS 2010, so to get that code snippet to work in VS 2003, you'll need to rejigger the code to use a function or functor object.

I think that something like the following might work for you:

// somewhere where it would be syntactically valid to 
//  define a function
void treenode_deleter(treenode* node)
{
    delete node;
}


// ...

bree::porder(m_root, treenode_deleter); 
Satiety answered 24/7, 2011 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.