`

c++ - Friend declaration in class Template

    博客分类:
  • c++
c++ 
阅读更多

There are three kinds of friends declaration that may appear within a class template. 

 

A nontemplate friend class or friend function.

 

 

/** - A nontemplate friend class or friend function.
* A nontemplate friend class or friend function. In the following example, the function foo(), the member function bar()
* the member function bar() and the class foobar are friends to all instantiation of the class tepmlate QueueItem .
*  
*  this is a one-to-one relationship and the fiends are determined/fixed right in the declaration (there is only one declaration of the friends)
*/
class Foo {
	void bar();
};

class foobar {}

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

 

 

It is the one-to-one relationship, and there is only one function . and no matter how many instance of the function template , there is only one declaration. 

 

A Bound friend class template or function template.

 

 

/** - A bound friend class template or function template 
*   this is a one-to-one relationship and the friends are not determined (the friends is created when the class is instantiated).-
*/
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 class foo<Type>(QueueItem<Type>);
	friend class Queue<Type>::bar();
};
 

 

this is also a one-to-one relationship, but for a particular instantiation of the class template, there is one friend for that instantiation.

 

 

An unbound friend class

 

 

 

/** - An unbound friend class template or function template 
*  unbound friend classes are multiple-to-one relationship
*   
*/
template <class Type>
template QueueItem
{
	friend class foobar;
	template <class T>
	friend void foo(QueueItem<T>);
	template <class T>
	friend void Queue<T>::bar();
};
 

There is a one-to-many relationship, where for a particular instantiation of the class template, there could be many function/classes that are the friends of the class template instantion. 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics