RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Taming Friends for Use in Templates-2 : Page 2

Non-template Friends
Let's start with the basics. Suppose you have a class template A that has to declare:
  • an ordinary function f()
  • an ordinary class C
as its friends. Friend declarations within a class template look like this:

class C {};
void f (int);

template <typename T> class A
  friend class C;
  friend void f (int);
A <int> xi;
A<std::string> xs;
In each specialization of the template A, f() and C are friends.

Note that the access specifiers don't affect friend declarations. Thus, you may move the friend declaration to the private or protected section of the class without changing its semantics in any way. However, the common practice is to declare friends as public.

You should always provide the elaborated type specifiers of the befriended entity in a friend declaration. In other words, the following declaration is invalid, although some compilers may accept them:

template <typename T> class X
  friend C; //error, missing 'class' before C

Befriending Templates
Declaring a class template as a friend of another class template is a bit different. In this case, the friend keyword appears after the template declaration:

template <typename U> class A{/*...*/};

template <typename T> class B
 template <typename U> friend class A;
Here, every specialization of A (e.g., A<int>, A<bool>, etc.) is a friend of every specialization of B.

Sometimes however, you want to restrict friendship to specific specializations of the befriended template. For example, you can allow A<int> to be a friend of every specialization of B, while denying friendship from all other specializations of A. In order to grant friendship selectively, declare the befriended specialization(s) as follows:

template <class U> class A{/*…*/};

template <class T> class B
 // only A<int> and A<string> are friends 
 friend class A <int>;
 friend class A <std::string>;


Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date