What friend declaration should go in the template class bar in order to grant friendship to the template function foo? Is that even possible, or do I have to write the definition of foo inside bar?
Yes, it's possible butr you need toi clearly understand hiow templates work. That is, you cannot have a function prototype be a template.
Therfore, you cannot have a friend function be a template that's outside the class template.
There are two cases:
1) Bound friend functions
2) Unbound friend functions.
A bound friend function can be a template function but not a function template.
That is, you can use an already specialized template:
-
template <class T>
-
void BoundFriend(T arg)
-
{
-
-
}
-
template <class T>
-
class MyClass
-
{
-
public:
-
friend void BoundFriend(int);
-
};
-
int main()
-
{
-
MyClass<double> obj;
-
}
-
The second case is the
unbound friend. Here the type used in the friend is not known until the object is created. Therefore, the unbound friend will be whatever type was used to create the template class. Therefore, you cannot have a prototype of the friend inside the class template. Therefore, you must insert the entire friend function template inside the class template:
-
template <class T>
-
class MyClass
-
{
-
public:
-
template <class T>
-
friend void UnBoundFriend(T arg)
-
{
-
-
}
-
};
-
int main()
-
{
-
MyClass<double> obj;
-
}
-
Finally, I am picking my words carefully to avoid misunderstanding:
class template -> this is the template itself
template class -> the specialized template created from a copy of the class template.
-
template <class T>
-
class MyClass //the class template
-
{
-
-
};
-
//
-
int main()
-
{
-
MyClass<int> obj; //MyClass<int> is the template class.
-
}
-
The same is true with functions:
function template -> this is the template itself
template function -> the specialized template created from a copy of the function template.