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?
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?
Share Improve this question edited Nov 27, 2024 at 14:28 Saitama10000 asked Nov 27, 2024 at 14:05 Saitama10000Saitama10000 2944 silver badges10 bronze badges 4- @wohlstad yes, any template types. – Saitama10000 Commented Nov 27, 2024 at 14:14
- You mean like in cppreference - Template friends examples? – pptaszni Commented Nov 27, 2024 at 14:16
- @Saitama10000 I posted an answer with both options. – wohlstad Commented Nov 27, 2024 at 14:17
- @wohlstad can you add the third option of only some parameters? thank you :) – Saitama10000 Commented Nov 27, 2024 at 14:19
1 Answer
Reset to default 5I 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