Internal functions related to variables from a scope

I have a piece of code like this:

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

Besides the iterator increment magic, which cannot be too obvoius here without comment, I would like to define a function double alpha()to reduce duplication. But since the use of this function is very specific, I would like to make it local. Perfectly:

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

In languages ​​like Python, this will be fine, but how to do it in C ++?

EDIT:

Here is what I got, special thanks to @wilx and flags -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();
+5
source share
3 answers

In this case, I would suggest using overload, for example angle2(std::list<Point> const &, etc.). Two simple arguments are better than yours now.

++ 11 lambdas, .

++ 11, , Boost.Phoenix( Boost.Spirit).

+1

++ , :

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

  int a = Inner::nestedFnc();
}
+2

C ++, as far as I know, does not allow this. You can limit the namespace pollution created by adding a static classifier to the top of the function signature for alpha, but you still need to define it separately.

This will only allow the name to be used in this source file. You can also define a macro inside a function, trying to prevent it from being defined unless you later want preprocessing weirdness.

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

All Articles