Tuesday, November 24, 2009

Friend Functions in C++

Friend:

==> adding a Friend function to a class template

Lesson1 :
void f (int);


template <> class A
{
public:
//...
friend void f (int);
};

A <> xi;
A<> xs;

In each instance of the Class A , f() functin is friend.


Lesson 2 :

When we are declaring a class as a friend of another class For ex:

class Brother
{

};

class Sister
{
public:
friend Brother; // Incorrect - Compilation error
}

The above will give compilation error, because friend declarations should have elaborated type specifiers. So, Sister class should be

class Sister
{
public:
friend class Brother; // Correct No compilation error
};



Lesson 3 :
Making a template as a friend to another template

template <>
class Brother
{

};

template
class Sister
{

public:
template <> friend class Brother;
};

above, every specialization of Brother (eg: Brother, Brother) will be a friend every specialization of Sister.

Lesson 4 :

Restricting friendship for only particular specialization

template <>
class Sister
{
public:
friend class Brother <>;
friend class Brother <>;
}

In above example, only the elderBrother and youngerBrother instances of Brother are friend classes to Sister class.(Not every instance of Brother)


Lesson 5 : Function Templates

Making friend function for Function Templates is little tricky and complex as it is not straightforward as above. For example:

class PhoneBook
{

};

template <>
int getCount(typename T, int maxRange)
{

}

To make the getCount() function as friend function for the class PhoneBook:

class PhoneBook ; //Forward Delcaration

template <>
int getCount(typenname T, int maxRange)
{
//Defination of functiont emplate
}


class PhoneBook
{

public:
friend int getCount<> (typeName T, int maxRange);
};


If we would like to avoid forward declaration of class followed with Function template defination and then follwed by including in class or class template. we can do the same in single stretch as below

class PhoneBook
{

public :
friend int getCount(typeName T, int maxRange)
{
//Implement here
}
};

To make a specialized version of getCount function template as a friend to PhoneBook then we can do as below
class PhoneBook
{
public:
friend int getCount<>(typeName T, int maxRange); //Where TELUGU may be another class or type
};

and implementation would be similar to function template with specialization as below:

template < >
int getCount<>(typeName T, int maxRange)
{
//Special implemenmtation for TELUGU
}

template <>
int getCount(typeName T, int maxRange)
{

//Generic implementation for other than TELUGU type.
}

Or as below (copy pasted from stl_hashtable.h)
template <>
class hashtable
{
:
:
public:
template <>
friend bool operator== (const hashtable<>&, const hashtable<>&);
}
If we define the specialization of function template within the friend declaration it will give compilation error.



No comments:

Post a Comment