Simulating nested functions in C++

霸气de小男生 提交于 2019-11-30 02:57:31

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

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