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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Taming Friends for Use in Templates-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 { public: //... 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 { public: //... 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 { public: //... 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 { public: // only A<int> and A<string> are friends friend class A <int>; friend class A <std::string>; };

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



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