A friend with a specific template class: "template <ANY ...> friend class A;"
Is there a way to declare a friend with a wildcard template class?
Example
I always declare a friend like this: -
//B.h
template<class T1,class T2>class B{};
//C.h
class C{
template<class,class> friend class B;
};
However, if the B
template argument is changed, I'll have to update C
, which is usually a header that is split far apart from each other.
//B.h
template<int T3,class T1,class T2>class B{};
//C.h
class C{
template<int,class,class> friend class B; //<-- manually update here too
};
This causes a minor maintainability issue. (For me, once a week.)
Question
Can I do something like this?
class C{
template<ANY...> friend class B;
};
Is it just impossible?
I faintly feel that this question might be duplicated because this is probably a common problem.
However, I cannot find it.
+3
source to share
1 answer
Here's one way:
// declare the concept of a variadic B
template<class...Ts> struct B;
struct C
{
private:
// any B with any number of Types is a friend
template<class...Ts> friend struct B;
void privateThing() {};
};
// now specialise B <T1, T2>
template<class T1, class T2> struct B<T1, T2> {
void foo(C& c) {
c.privateThing();
}
};
int main()
{
C c;
B<int, double> b;
b.foo(c);
}
+2
source to share