IS4
IS4

Reputation: 13177

How to match template friend function in a template class

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>?

Upvotes: 5

Views: 102

Answers (1)

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.

Upvotes: 4

Related Questions