无法了解模板类中的朋友功能 [英] Cannot understand friend functions in a template class

查看:62
本文介绍了无法了解模板类中的朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我为理解该概念而编写的代码.该代码很好,它可以运行.

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

推荐答案

根据[temp.friend],您必须提供明确的模板参数以使模板函数成为朋友:

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

没有它,编译器将寻找函数print(),而不是函数模板print().

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

这篇关于无法了解模板类中的朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆