# Class definition inside method body?

## Recommended Posts

Harry Hunt    542
I just found this "gem" on the web:
#define lambda(arguments, returnType, body)     class __LAMBDA##__LINE__ {         public:             returnType operator() arguments { body; }     }


Using this macro you can create functors on the fly using a relatively pretty syntax:
int main()
{
lambda((int a, int b), int, return a + b) add;
std::cout << sum << std::endl;
return 0;
}


int main()
{
class __LAMBDA3 {
public:
int operator() (int a, int b) { return a + b; }
std::cout << sum << std::endl;
return 0;
}


My question now is if this is even legal C++? It compiles just fine with Visual C++ but obviously that's no guarantee it's covered by the standard. If it is indeed legal, is there any reason why one shouldn't use something like this (besides the general evilness of macros)?

##### Share on other sites
ToohrVyk    1595
Yes, it's legal to define a class in a function body. This is indeed the way many lambda packages work.

##### Share on other sites
Harry Hunt    542

So there's nothing wrong with this? I read somewhere that there are ways of simulating lambdas without resorting to macros?

##### Share on other sites
SiCrane    11839
There is one caveat that I can think of: types defined inside a function lack linkage and so cannot be used with templates.

##### Share on other sites
Harry Hunt    542
Ah, thanks for the info. This shouldn't be a problem though.

##### Share on other sites
stonemetal    288
I think it is allowed. Boost lambda must do something similar only with templates.