Three cases in the C ++ template class friend (friend class, friend function) declared

According narrative "C ++ Primer" the third edition of the 16.4, C ++ template friend class is divided into the following situations
1. The non-template friend class or friend functions. One example given in the book: 

class Foo
{
    void bar();
};

template <class T>
class QueueItem
{
    friend class foobar;
    friend void foo();
    friend void Foo::bar();
    //....
};

Note that, if we want a normal function and a friend class declaration of the foregoing need not be declared or defined. However, if we want a class member function is declared as a friend, it must be preceded by the definition of the class (note not a statement is defined) as a class member can only be introduced by the definition of the class.

2. bound friend class or function template. Examples are as follows:

template <class Type>
class foobar{ ...};

template <class Type>
void foo(QueueItem<Type>);

template <class Type>
class Queue
{
    void bar();
    //...
};

template <class Type>
class QueueItem
{
    friend class foobar<Type>;
    friend void foo<Type>(QueueItem<Type>);
    friend void Queue<Type>::bar();
    //...
};

Note the following two points:

a. with non-template function or class, the template function or class declaration must be declared in front of a friend as before, or can not compile.
b. When a template class or function declaration as a friend, after their names to add Type, otherwise it will compile error. For example, for a normal function foo, if not increase, then the compiler will treat it as a non-template function, that is, for QueueItem, the compiler looks for void foo (QueueItem), while the template <class Type> void foo ( QueueItem < Type>) turn a blind eye, if not find a non-template function, the compiler will report an error.

3. Non-binding friend class or function template. For example as follows:

template <class Type>
class QueueItem
{
    template <class T>
    friend class foobar;

    template <class T>
    friend void foo(QueueItem<T>);

    template <class T>
    friend void Queue<T>::bar();
    //...
};

 

Released three original articles · won praise 0 · Views 98

Guess you like

Origin blog.csdn.net/qq_33669963/article/details/103985285