# Nested functions in c++

## Recommended Posts

It seems to me that you could create pseudo nested functions in c++ by doing something like this:
int blah()
{
// let's do a nested function!
class nested_function
{
public:
int operator()(int foo)
{
// do stuff
return 1000;
}
};

int woohoo = nested_function(123);
}


That's kind of ugly though. It'd be nice to use a few #define's and make something a little nicer, maybe something like this:
declare_nested_function(blah)(int x)
// do stuff
end_nested_function

But I can't seem to come up with any #define's that make it any cleaner. Has anyone else ever done anything like this before?

##### Share on other sites
#define declare_nested_function(RET, NAME)   \ struct NAME                                  \ {                                            \     RET operator()                           /**/#define end_nested_function };               /**/declare_nested_function(char, blah)(int i){    return (char)i;}end_nested_functionchar a = blah(42);

Of course, there's little point to this, it doesn't allow you to use any local variables from the original function, and there's no way to "automate" it with defines (that I can think of). You could do it manually, but not automagically.

## 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