asheeshr
asheeshr

Reputation: 4114

Cannot understand friend functions in a template class

This is code i have written to understand the concept. The code is fine and it runs.

What i dont understand is that why is the marked line needed ?

template <class T>
class D
{
    public :
    template <class P>  //<------------------Why is this needed ? --------------
    friend void print(D <P> obj);
};

template <class T>
void print(D<T> obj)
{std::cout<<sizeof(T);};


int main()
{
    D <char>obj3;
    print(obj3);
    return 0;
}

or in other words why does the following not run ?

template <class T>
class D
{
    public :
    friend void print(D <T> obj);
};

Upvotes: 7

Views: 862

Answers (1)

As per [temp.friend], you must provide explicit template arguments to make a specialisation of a template function a friend:

template <class T>
class D
{
    public :
    friend void print<T>(D <T> obj);
};

Without it, the compiler will be looking for a function print(), not a function template print().

Upvotes: 10

Related Questions