Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match template friend function in a template class

Tags:

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

like image 652
IS4 Avatar asked Jan 22 '18 13:01

IS4


People also ask

Can template function friends?

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.

Can a friend function be defined within a class?

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).

Is class template and function template the same?

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.

Can a non-template class have a template member function?

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.


1 Answers

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.

like image 145
StoryTeller - Unslander Monica Avatar answered Sep 21 '22 12:09

StoryTeller - Unslander Monica