现在C++中有lambdas,我无法声明本地函数似乎真的很愚蠢......
例如:
我可以在函数体中声明一个类型,甚至可以将其初始化为值表.但我无法创建一个与该数据类型一起使用的辅助函数 - 因为我无法在函数中声明函数,并且我不能在函数外部引用该数据类型,因为它仅在该范围内可用.
有时候将数据类型从函数中拉出来很简单,并在那里定义我的数据类型和辅助函数(本地文件范围) - 但有时它并不是真正合理的解决方案 - 例如在初始化表时内联lambda引用局部范围变量(或this).
是否已经定义了对本地函数的支持是否已经定义,或者为什么编译器编写者难以实现,因此不是标准的一部分?
rod*_*igo 24
没有本地函数,但没有闭包它们就没那么有用,也就是访问局部变量.在任何情况下,您都可以使用lambda轻松模拟本地函数.
代替:
void foo(int x)
{
struct S
{
//...
};
int Twice(int n, S *s) //Not allowed
{
return 2*n;
}
S s;
int x = Twice(3, &s);
//...
}
Run Code Online (Sandbox Code Playgroud)
做:
void foo()
{
struct S
{
//...
};
auto Twice = [](int x, S *s) -> int //Cool!
{
return 2*x;
}; //Twice is actually a variable, so don't forget the ;
S s;
int x = Twice(3, &s);
//...
}
Run Code Online (Sandbox Code Playgroud)
如果捕获集为空,([])它甚至可以转换为普通的指向函数的指针,就像真正的指针一样!
而AFAIK,lambdas可以毫无困难地使用本地类型.但是,当然,该结构中的公共静态成员函数也可以正常工作.
作为另外一个与您的问题间接相关的注释,C++ 11中允许的是使用本地类型(在C++ 98中禁止)实例化模板:
void foo()
{
struct S {};
std::vector<S> vs; //error in C++98, ok in C++11
}
Run Code Online (Sandbox Code Playgroud)