模板朋友功能的前向声明 [英] Forward declaration of template friend function

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

问题描述

考虑以下运行良好的代码段:

Consider the following code snippet that works perfectly fine:

class A
{
private:
    int d;
public:
    A(int n){ d = n;}
    friend int foo(A a);
};

int foo(A a)
{
    return a.d;
}

但是,当我尝试为该类使用模板时,需要向前声明要运行的朋友函数,如下所示:

However, when I try to use a template for the class, I need to forward declare the friend function for it to run, as follows:

template <typename T>
class B;

template <typename T>
T foof(B<T> a);


template <typename T>
class B
{
private:
    T d;
public:
    B(T n){ d = n;}
    friend T foof<>(B<T> a);
};

template <typename T>
T foof(B<T> a)
{
    return a.d;
}

为什么在第二个示例中需要前向声明,而在第一个示例中却不需要?另外,为什么我必须在类B内的foof声明中放入<> ?为什么在模板内部声明它还不够?我试图了解这些事情是如何工作的,以便在我需要使用这种代码时不必盲目地记住这种代码.

Why is the forward declaration necessary in the second example but not on the first one? Also, why do I have to put <> in the declaration of foof inside class B? Why isn't it enough that it is declared inside of the template? I am trying to understand how these things work so that I don't have to blindly memorize this kind of code when I need to use it.

谢谢

推荐答案

那是因为

friend int foo(A a);

是功能的声明,同时是朋友,但是:

is declaration of function and a friend at the same time, but:

friend T foof<>(B<T> a);

是模板实例化的朋友声明.那不一样.实例化没有声明模板功能.

Is friend declaration to template instantiation. That's different. Instantiation doesn't declare template function.

您可以成为整个函数模板的朋友,然后不需要前向声明:

You could befriend whole function template, and then forward declaration isn't needed:

template <typename T>
class B
{
private:
    T d;
public:
    B(T n){ d = n;}
    template<class U>
    friend U foof(B<U> a);
};

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

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