Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this even doable?

>Solution :

I assume you want Obj with any template types to be a friend.

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 matching types to be a friend, the syntax for that is:

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

Live demo 2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading