处理范围内变量的内部函数

Inner functions dealing with variables from the scope

本文关键字:内部函数 变量 范围内 处理      更新时间:2023-10-16

我有这样一段代码:

std::list<boost::shared_ptr<Point> > left, right;
// ... fill lists ...
// now, calculate the angle between (right[0], right[1]) and (right[0], left[0])
double alpha = angle(*(right.begin()->get()), *(((++right.begin()))->get()), *(left.begin()->get()) );
std::cout << alpha * 180 / M_PI << std::endl;
if(alpha < 0){
    // do something with the lists, like reversing them. Especially the beginning and end of the lists may change in some way, but "left" and "right" are not reassigned.
}
// calculate the new alpha
alpha = angle(*(right.begin()->get()), *(((++right.begin()))->get()), *(left.begin()->get()) );

除了迭代器的增量魔法(如果没有注释,可能不太明显)之外,我想定义一个函数double alpha()来减少重复。但是因为这个函数的用途是非常特殊的,所以我想让它成为一个局部函数。理想情况是这样的:

int a, b;
int sum(){ return a + b; }
a = 5; b = 6;
int s = sum(); // s = 11
a = 3;
s = sum(); // s = 9 now

在像Python这样的语言中,这是完全可以的,但是在c++中如何做到这一点呢?

编辑:

这就是我最终得到的,特别感谢@wilx和-std=c++0x编译器标志:

auto alpha = [&right, &left]() {
    // not 100% correct due to my usage of boost::shared_ptr, but to get the idea
    Point r_first = *(right.begin()); 
    Point l_first = *(left.begin());
    Point r_second = *(++right.begin());
    return angle(r_first, r_second, l_first);
};

if(alpha() < 0) // fix it
double new_alpha = alpha();

c++不支持嵌套函数,但是可以使用函数作用域类来解决这个问题:

void scopeFnc()
{
  struct Inner
  {
     static int nestedFnc() { return 5; }
  };
  int a = Inner::nestedFnc();
}

在这种情况下,我建议使用像angle2(std::list<Point> const &, etc.)这样的过载。两个简单的参数比你现在的好。

在c++ 11中,你可以使用lambdas通过引用捕获它们的参数。

如果你不能使用c++ 11,你想冒险,试试Boost。凤凰号(Boost.Spirit的一部分)

c++,据我所知,不允许这样做。您可以通过在alpha函数签名的开头附加静态限定符来限制命名空间污染,但是您仍然必须单独定义它。

这将使该名称仅在该源文件中使用。你也可以在函数中定义一个宏,如果你不希望以后出现预处理异常,请小心取消定义。

int a, b;
#define SUM() (a+b)
int s=sum()
#undef SUM