我在VS2010中遇到编译错误,我不知道是否应该将其视为编译器错误:
我尽可能地简化了场景:模板类被声明为某个类的友元,并尝试在 lambda 函数内访问该友元的私有(private)成员。代码如下:
class Foo {
template<typename T> friend class Bar;
int priv;
};
template<typename T>
class Bar {
public:
void func() {
Foo foo;
foo.priv = 17; // compiles
auto lambda_func = [](Foo& _foo) { _foo.priv = 17; }; // doesn't compile
}
};
void test() {
Bar<int> bar;
bar.func();
}
请注意,只有当 Bar 是模板类时才会发生这种情况。
最佳答案
这在 g++ 4.6 和 4.7 中编译得很好。我认为这也是合法的 --- lambda 应该具有与其定义的函数一样多的访问权限。
C++11 标准 5.1.2p7 表示(添加了强调):
The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator, but for purposes of name lookup (3.4), determining the type and value of this (9.3.2) and transforming id-expressions referring to non-static class members into class member access expressions using (*this) (9.3.1), the compound-statement is considered in the context of the lambda-expression.
我认为这意味着封闭 block 中有效的任何内容在 lambda 主体中也有效。
MSVC2010 还有其他 lambda 错误,因此它无法编译此案例并不令我感到惊讶。
关于c++ - Visual Studio 2010 中的友元模板类和 Lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10160489/