c++ - Visual Studio 2010 中的友元模板类和 Lambda 函数

标签 c++ visual-studio-2010 lambda c++11 friend

我在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/

相关文章:

visual-studio-2010 - Visual Studio 2010 并排运行时会丢失用户设置

带有 lambda 的 Java 默认方法

c++ - 为什么在这段代码中编译器选择 r-value ref 版本

c++ - 如何克服 make_shared constness

c++ - bool 函数返回意外值

mysql - 我可以在 MySQL 中使用 "Hide"列吗?

c++ - Visual Studio 2010 的全局源代码控制忽略模式中应包含哪些内容?

c++ - 如何使用 boost::filesystem 计算目录中的文件数?

c++ - 我正在尝试传递一个 lambda 作为参数

c++ - 正 lambda : '+[]{}' - What sorcery is this?