C++ Friend function of nested class in class template
Asked Answered
S

0

6

I'm having the following problem. The code below runs fine on gdb online, however locally compiling like this:

/.../g++ -std=c++17 -g -O3
/.../Test.cpp -o
/.../Test

produces:

error:
'privateMember' is a private member of 'Foo<int>::Nested'

I also tried with VS2019 - same effect as g++ (which is really a clang: Apple clang version 11.0.0 (clang-1100.0.33.8)).

What fixes this issue is: changing call (comment "//2")

make(...) -> make<int>(...)

or

removing line with comment "//1".

The fixes are independent from each other - only one needs to be applied.

template <typename T>
class Foo;

template <typename T>
typename Foo<T>::Nested make(T&& t);

template <typename T>
class Foo
{
public:
    class Nested
    {
        int privateMember{5};
        friend Nested make<T>(T&& e);
    };

    Nested k; //1
};

template <typename T>
typename Foo<T>::Nested make(T&& t)
{
    typename Foo<T>::Nested nested{}; 
    std::cout<<nested.privateMember<<std::endl;
    return nested;
}

int main() {
    auto i = make(1); //2
    return 0; }

Can somebody explain to me what is happening here? Why the code runs fine on gbd online and not with g++, also why the changes (1, 2) help?

Sprage answered 8/11, 2019 at 8:40 Comment(5)
msvc does not seem to complain about the private member, but a missing overload. Is your g++ really clang? Can you add the output of g++ --version? gcc compiles this fine, no matter what version I choose. See godbolt.org/z/d3QGKfAudly
GCC 9.2 does not complain about this code...Detest
@uneven_mark correct - this is the error message I'm getting as well with mdvc. EDIT: my g++ indeed is a clang: 'Apple clang version 11.0.0 (clang-1100.0.33.8)'Massey
@TonvandenHeuvel I edited my post, my g++ is actually a clang compiler.Massey
Set up working, non-working cases here: godbolt.org/z/m5YfvF . So weird that explicitly specifying the template fixes it. I know it's never a compiler bug, but it sure feels like a compiler bugBlossom

© 2022 - 2024 — McMap. All rights reserved.