c++templatesfriend

How do I make this templated class be a friend of another class?


I'm trying to get access to members from another templated class and it doesn't let me. The issue is I don't know why.

#include <iostream>
    
template <typename T0, typename T1, typename T2, typename T3>
struct Obj{};
    
template <typename T0, typename T1, typename T2, typename T3>
struct Obj2
{
    template <typename U0, typename U1, typename U2, typename U3> 
    friend Obj<U0, U1, U2, U3>;
    
    template <typename T> 
    Obj2(Obj<T, T0, T1, T2> const&) {}
};
    
int main() {}

Output:

<source>:10:31: error: expected unqualified-id before ';' token [-Wtemplate-body]
   10 |     friend Obj<U0, U1, U2, U3>;
      |                               ^
Compiler returned: 1

Godbolt link: code

Is this even doable?


Solution

  • I assume you want Obj with any template types to be a friend.
    This means that any instantiation of Obj will be a friend of Obj2.

    In this case the proper syntax is:

    template <typename U0, typename U1, typename U2, typename U3> 
    friend struct Obj;
    

    Live demo 1

    If on the other hand you wish only Obj with template types that match those of Obj2 to be a friend, the syntax for that is:

    friend struct Obj<T0,T1,T2,T3>;
    

    Live demo 2