处理范围内变量的内部函数
Inner functions dealing with variables from the scope
我有这样一段代码:
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
相关文章:
- C++ SSE 内部函数:将结果存储在变量中
- C++代码停止工作错误使用cout内部函数
- 为什么从具有较大阵列的 SIMD 内部函数中获得的相对加速比标量更大?
- 未使用的C++未优化的静态成员函数/变量
- 使用英特尔内部函数 (AVX) 中的混合说明
- 英特尔汇编与内部函数,AVX
- 内联函数/变量的外部链接
- 使用SSE内部函数复制少量数据时出现问题
- 在为函数编写单元测试时,我应该模拟所做的内部函数调用吗?
- 用于平铺矩阵乘法的 AVX 内部函数
- 是否可以使用类的析构函数内部函数来重置值?
- 我在理解 AVX 随机内部函数如何为 8 位时遇到一些问题
- 无法执行内部函数 strlen
- COUT 内部函数调用的顺序
- GCC(通过 CUDA)内部函数的编译器错误,但我没有使用任何
- 同一函数中的静态函数变量初始化顺序
- 函数内部静态变量的内存分配
- 在C++中的类的函数内部声明变量
- 处理范围内变量的内部函数
- 使用auto将类声明为函数内部的变量