• Advertisement
Sign in to follow this  

Nested functions in c++

This topic is 4711 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement

#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_function
char 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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement