Say I have two Template classes.
template<class T>
class baseclass1
{
template<class> friend class baseclass2;
}
template<class D>
class baseclass2
{
template<class T> void foo( D& x, T& y)
{
...
}
}
The Above code allows all types of baseclass1 to friend all types of baseclass2, a many-to-many relationship. I have two questions,
What is the syntax to allow baseclass1 to friend just the function
baseclass2<class D>::foo<class T>( D& x, T& y).
And, what is the syntax to allow baseclass1 to friend just the function
baseclass2<class D>::foo<class T>( D& x, T& y) where T from baseclass1 matches The T from Function foo.
EDIT
To those who keep claiming you can’t friend a template specialization. This code works
template<class cake>
class foo
{
public:
static void bar(cake x)
{
cout << x.x;
}
};
class pie
{
public:
void set( int y){ x = y; }
private:
int x;
friend void foo<pie>::bar(pie x);
};
class muffin
{
public:
void set( int y){ x = y; }
private:
int x;
friend void foo<pie>::bar(pie x);
};
int main
{
pie x;
x.set(5);
foo<pie>::bar(x);
muffin y;
y.set(5);
//foo<muffin>::foo(y); //Causes a compilation Error because I only friended the pie specialization
}
Even notice where muffin friends the wrong foo, and still causes a compilation error. This works with both functions and classes. I am totally willing to accept that this isn’t possible in my specific situation (It’s actually looking more and more that way) I’d just like to understand why.
Befriending all possible specializations of
baseclass2<D>::foois rather easy:Live example.
A forward declaration of
baseclass2(sobaseclass1knows thatbaseclass2exists and is a template) and two templates, one for the class, one for the function. It also looks like this for out-of-class definitions for function templates of class templates. 🙂Befriending specifically
baseclass2<D>::foo<T>is not possible, however, or I can’t findthe correct syntax for it.
A workaround might be some global function that forwards the access and together with the passkey pattern, but meh, it’s a mess (imho):
Live example.