Cannot understand friend functions in a template class

五迷三道 提交于 2019-12-10 18:49:50

问题


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

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



来源:https://stackoverflow.com/questions/13451867/cannot-understand-friend-functions-in-a-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!