Sign in to follow this  
Harry Hunt

Class definition inside method body?

Recommended Posts

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;
    int sum = add(4, 5);
    std::cout << sum << std::endl;
    return 0;
}

Now I thought about this for a sec and I realized that this would expand to:
int main()
{
    class __LAMBDA3 {
        public:
            int operator() (int a, int b) { return a + b; }
    } add;
    int sum = add(4, 5);
    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 this post


Link to post
Share on other sites
Thanks for the reply!

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

Share this post


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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this