首页 > 解决方案 > 为什么 lambda 上的朋友声明在 gcc 上不起作用

问题描述

看这个简单的例子,

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();
}

朋友声明似乎不起作用。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{}

神螺栓

标签: c++lambda

解决方案


推荐阅读