简体   繁体   中英

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);
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM