Simulating nested functions in C++

2019-02-02 04:03发布

In C the following code works consider I always use gcc.

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

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

7条回答
Animai°情兽
2楼-- · 2019-02-02 04:08

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

查看更多
Fickle 薄情
3楼-- · 2019-02-02 04:14

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

查看更多
够拽才男人
4楼-- · 2019-02-02 04:17

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楼-- · 2019-02-02 04:18

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

查看更多
Luminary・发光体
6楼-- · 2019-02-02 04:28

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
    ...
}
查看更多
虎瘦雄心在
7楼-- · 2019-02-02 04:29

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);
}
查看更多
登录 后发表回答