Simulating nested functions in C++

夙愿已清 提交于 2019-12-08 23:14:54

问题


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.


回答1:


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




回答2:


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



回答3:


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
    ...
}



回答4:


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.




回答5:


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



回答6:


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




回答7:


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




回答8:


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



来源:https://stackoverflow.com/questions/5356050/simulating-nested-functions-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!