Simulating nested functions in C++

Paul McCutcheon picture Paul McCutcheon · Mar 18, 2011 · Viewed 17.1k times · Source

In C the following code works in gcc.

int foo( int foo_var )
{
 /*code*/
  int bar( int bar_var )  
  {
    /*code*/
    return bar_var;
  }
  return bar(foo_var);
}

How can I achieve the same functionality of nested functions in C++ with the gcc compiler? Don't mind if this seems like a beginner question. I am new to this site.

Answer

Ben Voigt picture Ben Voigt · Mar 18, 2011

Local functions are not allowed in C++, but local classes are and function are allowed in local classes. So:

int foo( int foo_var )
{
 /*code*/
  struct local 
  {
    static int bar( int bar_var )  
    {
      /*code*/
      return bar_var;
    }
  };
  return local::bar(foo_var);
}

In C++0x, you would also have the option of creating a functor using lambda syntax. That's a little more complicated in C++03, but still not bad if you don't need to capture variables:

int foo( int foo_var )
{
 /*code*/
  struct bar_functor
  {
    int operator()( int bar_var )  
    {
      /*code*/
      return bar_var;
    }
  } bar;
  return bar(foo_var);
}