devxlogo

Declare a Function Template as a Friend of Another Class Template

Declare a Function Template as a Friend of Another Class Template

There are various forms of friend declarations within a class template: a non-template friend, a specialized template friend, and a class template friend. A function template can also be declared as a friend of a class template. For instance, you might add an overloaded operator == function template to test the equality of two Vector objects. By doing so, you ensure that for every specialization of Vector, the implementation will generate a corresponding specialization of the overloaded operator == as well. Unfortunately, the declaration of a function template friend is rather complex. This following example walks you through these intricate steps and demonstrates how to do the declaration.

In order to declare a template function as a friend, you first have to forward declare the class template and the friend function template as follows:

   template  class Vector; // class template forward declaration    // forward declaration of the function template to be used as a friend  template  bool operator== (const Vector& v1, const Vector& v2);

Next, you declare the friend function template inside the class body:

   template  class Vector  {  public:    //

devx-admin

Share the Post: