为什么 lambda 上的朋友声明在 gcc 上不起作用

Hui*_*Hui 6 c++ lambda

看这个简单的例子,

constexpr auto f = [](const auto& foo){
    foo.fun2();
};

struct Foo{
    friend decltype(f);

    void fun1() const{
        f(*this);
    }

    private:
    void fun2() const{}
};

int main(){
    Foo foo{};
    foo.fun1();
}
Run Code Online (Sandbox Code Playgroud)

朋友声明似乎不起作用。gcc 抱怨fun2即使f获得了访问权限也是私有的。

这会导致编译器错误

<source>: In instantiation of '<lambda(const auto:1&)> [with auto:1 = Foo]':

<source>:9:16:   required from here

<source>:2:13: error: 'void Foo::fun2() const' is private within this context

    2 |     foo.fun2();

      |     ~~~~~~~~^~

<source>:13:10: note: declared private here

   13 |     void fun2() const{}
Run Code Online (Sandbox Code Playgroud)

神箭