templates

The Special Friendship of Templates

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, access rights in the class are not considered.
  3. Friendship is not inherited. When a class grants friendship to a class Derived, a  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 a friendship to class or class templates, function or function templates, or types.

General Friendship

A class or a class template can grant friendship to each instance of a class template or a 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';

}

 

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    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 unique 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 will write about dependent names, one of the more complicated corners of templates.

     

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery,and Matt Godbolt.

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

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

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

    Standard Seminars (English/German)

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

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *