문제

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.

도움이 되었습니까?

해결책

Turn your function into a functor as Herb Sutter suggests in this article

다른 팁

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);
}

use local functor

#define lambda(return_type, function_body) \
struct { return_type operator () function_body }


int main ()
{
    lambda(int, (int x, int y) { return x > y ? x : y; } ) maxFunc;
    int m = maxFunc(1,2); //=> 2
    ...
}

The construct that comes closest to nested functions is the C++11 lambda.

void SomeFunction(int x)
{
    int var = 2;
    auto lambda = [&] (int param) -> int { return var + param; };

    printf("var + x = %d\n", lambda(x));
}

Lamdas allow to use variables from the outer scope (the [&] specifies to automatically capture all variables from the outer scope by reference). A lambda, that does not use any variables from the outer scope (use []) can be converted to a function pointer of the same type and can thus be passed to functions accepting a function pointer.

You could try using boost::phoenix (v2 is a subpackage of spirit, v3 is in svn/trunk as it's own package and should be in 1.47)

#include <boost/spirit/include/phoenix.hpp>
#include <boost/function.hpp>

using namespace boost::phoenix::arg_names;

int foo( int foo_var )
{
 /*code*/
  boost::function<int(int)> bar = _1 + 5;
  return bar(foo_var);
}

int main() {
return foo(1);
}

In C++ you may achieve the same effect by other possible means. There are no direct nested function implementations. Two helpful links:

http://www.respower.com/~earlye/programming/19990916.001.htm

http://www.devx.com/tips/Tip/40841

AFAIK, nested functions are not allowed in C++.

I know this thread is old. But a C++11 solution would be to write lambdas and call them whenever wanted

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top