According to section 16.4 of the third edition of C ++ primer, the C ++ class template can be divided into the following situations:
1. Non-template friends or friends functions. Here is an example:
Class Foo {
Void bar ();
};
Template <class T>
Class queueitem {
Friend class foobar;
Friend void Foo ();
Friend void FOO: bar ();
//....
};
It is very simple. It is no different from non-template classes. Note that if you want to set the function and class life as a friend, you do not need to declare or define it before. However, if you want to declare a class member function as a friend, you must first define the class (not declaration, but definition), because a class member can only be introduced by the class definition.
2. Bind a membership template or function template. Example:
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 ();
//...
};
Pay attention to the following two points:
A. Unlike non-template functions or classes, template functions or classes must be declared before they are declared as friends; otherwise, they cannot be compiled.
B. Pay attention to the red-letter part. The types should not be less. For example, if <type> is missing for function Foo, the compiler treats it as a non-template function, that is, for queueitem <int>, the compiler looks for void Foo (queueitem <int>) and turns a blind eye to template <class T> void Foo (queueitem <t>). If no non-template function is found, an error is returned.
3. Non-bind user meta templates or function templates. Example:
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 ();
//...
};
From: http://blog.csdn.net/peimichael/article/details/4894000