It depends on what exactly you are trying to achieve. You may want to befriend a single instantiation of the template, or you might want to befriend all instantiations. Finally you might not really want to befriend a template, but just a non-templated function that is automatically generated by the compiler upon instantiation of your class template...
Befriending the whole template:
template <typename T>
class MyClass {
template <typename U>
friend MyClass<U> f();
};
Befriending a concrete instantiation (i.e. allowing f<int>
access to MyClass<int>
but not to MyClass<double>
):
// Forward declarations
template <typename T>
class MyClass;
template <typename T>
MyClass<T> f();
// Definition of class template
template <typename T>
class MyClass {
friend MyClass<T> f<T>();
};
// Definition of friend function
template <typename T>
MyClass<T> f() { ... }
Automatic instantiation of a befriended non-template function:
template <typename T>
class MyClass {
friend MyClass<T> f() { ... } // define inline
};
I would recommend that you use the latter, unless the function is parametrized with other template parameters than the T
for MyClass<T>
.
Recommend reading: overloading friend operator<< for template class