I have a template class that declares a friend function which itself has template parameters. The code looks like this:
template <class T>
class C;
template <class T, class U>
void func(C<T>& t);
template <class T>
class C
{
template <class U>
friend void func<T, U>(C<T>& t);
private:
template <class U>
void f()
{
}
};
template <class T, class U>
void func(C<T>& t)
{
t.f<U>();
}
But when I try to call func
, I get a compilation error at the friend
line:
'func': no matching overloaded function found
How can I make func<T, U>
friend with C<T>
?
One-to-one: A template function instantiated with one set of template arguments may be a friend to one template class instantiated with the same set of template arguments. This is also the relationship between a regular non-template class and a regular non-template friend function.
Friend functions can be defined (given a function body) inside class declarations. These functions are inline functions. Like member inline functions, they behave as though they were defined immediately after all class members have been seen, but before the class scope is closed (at the end of the class declaration).
The difference is, that the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class. Function Templates We write a generic function that can be used for different data types.
A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.
The key issue is that the friend you declared, is not the same as the previous declaration you provided. The first expects two template parameters, but the second (friend) you defined to accept only one. Once that is resolved, everything works:
template <class T>
class C;
template <class U, class T>
void func(C<T>& t);
template <class T>
class C
{
template <class U, class TT>
friend void func(C<TT>& t);
private:
template <class U>
void f()
{
}
};
template <class U, class T>
void func(C<T>& t)
{
t.template f<U>();
}
int main() {
C<int> c;
func<bool>(c);
}
Watch it live.
Note I switched U
and T
up, because I assumed you may want T
deduced and U
explicitly specified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With