The Special Friendship of Templates

Contents[Show]

A friend has unrestricted access to the members of a class. Consequently, friendship should be given wisely. Regarding templates, friendship is special.

 templates

Before I write about the friendship rules for templates, I want to present the general rules about friendship.

  1. The friend declaration can be made in any place in the class.
  2. For friendship, the access rights in the class are not considered.
  3. Friendship is not inherited. When a class grants friendship to a class Derived, a from Derived derived class is not automatically a friend to Base.
  4. Friendship is not transitive. When class B is a friend of class A and Class C is a friend of class B, class C is not automatically a friend of class A.

A class or a class template can have friendship to class or class templates, function or function templates, or types.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.

 

 

General Friendship

A class or a class template can grant friendship to each instance of a class template or function template.

 

// generalFriendship.cpp

#include <iostream>

template <typename T>                            // (1)
void myFriendFunction(T);

template <typename U>                            // (2)
class MyFriend;

class GrantingFriendshipAsClass {

  template <typename U> friend void myFriendFunction(U);
  template <typename U> friend class MyFriend;

  std::string secret{"Secret from GrantingFriendshipAsClass."};

};

template <typename T>
class GrantingFriendshipAsClassTemplate{

  template <typename U> friend void myFriendFunction(U);
  template <typename U> friend class MyFriend;

  std::string secret{"Secret from GrantingFriendshipAsClassTemplate."};

};

template <typename T>                                // (3)
void myFriendFunction(T){
  GrantingFriendshipAsClass myFriend;
  std::cout << myFriend.secret << '\n';

  GrantingFriendshipAsClassTemplate<double> myFriend1;
  std::cout << myFriend1.secret << '\n';
}

template <typename T>                              // (4)
class MyFriend{
public:
  MyFriend(){
    GrantingFriendshipAsClass myFriend;
    std::cout << myFriend.secret << '\n';

    GrantingFriendshipAsClassTemplate<T> myFriend1;
    std::cout << myFriend1.secret << '\n';
  }
};

int main(){

  std::cout << '\n';

  int a{2011};
  myFriendFunction(a);

  MyFriend<double> myFriend;

  std::cout << '\n';

}

 

Line (1) and line (2) forward declare the function template myFriendFunction and the class template MyFriend. The function template myFriendFunction is defined in line (3) and the class template MyFriend in line (4). The classes GrantingFriendshipAsClass and GrantingFriendshipAsClassTemplate grant the function template myFriendFunction and the class template MyFriend friendship. Due to the friendship, both templates can directly invoke the private member secrete of the class and the class template.

generalFriendship

There is a pitfall involved in the class template GrantingFriendShipAsClassTemplate. Usually, you call the first type parameter of a template T. When you use - such as in the following code snippet - the same type parameter name for the class template and the function template myFriendFunction or the class template MyFriend, an error occurs. The name T of myFriendFunction or MyFriend shadows the name T of the class template GrantingFriendshipAsClassTemplate.

The following code snippet displays the pitfall.

template <typename T>
class GrantingFriendshipAsClassTemplate{

  template <typename T> friend void myFriendFunction(T);
  template <typename T> friend class MyFriend;

  std::string secret{"Secret from GrantingFriendshipAsClassTemplate."};

};

 

Special Friendship

A special friendship is a friendship that depends on the type of template parameter.

 

// specialFriendship.cpp

#include <iostream>

template <typename T> void myFriendFunction(T);
template <typename U> class MyFriend;


class GrantingFriendshipAsClass {

  friend void myFriendFunction<>(int);             // (1)
  friend class MyFriend<int>;                      // (2)

private:
  std::string secret{"Secret from GrantingFriendshipAsClass."};

};

template <typename T>
class GrantingFriendshipAsClassTemplate {

  friend void myFriendFunction<>(int);
  friend class MyFriend<int>;
  friend class MyFriend<T>;                        // (3)

private:
  std::string secret{"Secret from GrantingFriendshipAsClassTemplate."};

};

template <typename T>
void myFriendFunction(T) {
  GrantingFriendshipAsClass myFriend;
  std::cout << myFriend.secret << '\n';             // (4)

  GrantingFriendshipAsClassTemplate<T> myFriend1;
  std::cout << myFriend1.secret << '\n';            // (5)
}

template <typename T>                               // (6)
class MyFriend {                      
public:
  MyFriend() {
    GrantingFriendshipAsClass myFriend;                 
    std::cout << myFriend.secret << '\n';

    GrantingFriendshipAsClassTemplate<int> myFriendInt;  
    std::cout << myFriendInt.secret << '\n';

    GrantingFriendshipAsClassTemplate<T> myFriendT;      
    std::cout << myFriendT.secret << '\n';
  }
};

int main() {

  std::cout << '\n';

  int a{2011};
  myFriendFunction(a);                                    

  MyFriend<int> myFriend;                                 

  std::cout << '\n';

}

 

The class GrantingFriendshipAsClass grants friendship to the full specialization of the function template myFriendFunction for int (line 1) and the class template MyFriend for int (line 2). The same holds for the class template GrantingFrandshipAsClassTemplate. Lines (3) is special because it grants friendship to the full specialization for MyFriend having the same type parameter as the class template GrantingFrandshipAsClassTemplate. Consequently, the function template myFriendFunction can invoke the secret of the class GrantingFriendshipAsClass when myFriendFunctions is a full specialization for int (line 4) or GrantingFriendshipAsClassTemplate has the same type such as myFriendFunction (line 5). The corresponding argumentation holds for the class template MyFriend (line 6).

specialFriendship

Friend to Types

A class template can also grant its friendship to a type parameter.

 

// typeFriendship.cpp

#include <iostream>

template <typename T>
class Bank {
    std::string secret{"Secret from the bank."};
    friend T;
};

class Account{
 public:
    Account() {
        Bank<Account> bank;
        std::cout << bank.secret << '\n';   // (1)
    }
};

int main(){

    std::cout << '\n';

    Account acc;

    std::cout << '\n';

}

 

The class Bank grants friendship to its type parameter T. Consequently, an Account can access the secret of the bank instantiation for Account: Bank<Account> (line 1).

typeFriendship

What's next?

In my next post, I write about one of the more complicated corners of templates: dependent names.

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, and Phillip Diekmann.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, and Alicja Kaminska.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

 

 

Mentoring

Stay Informed about my Mentoring

 

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 6223

Yesterday 4527

Week 6223

Month 26970

All 10948431

Currently are 272 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments