Search code examples
c++classtemplatesfriendorganization

How to separate a template class from its friend template class into different header files?


A file contains template class A and template class B. A is friend of B.

I want to separate them into different files. How to deal with it?


Solution

  • A.h

    #if !defined(FILE_A_H)
    #define      FILE_A_H
    
    template<class T>
    class A
    {
      template<class> friend class B;
    
      // ...
    };
    
    #endif
    

    B.h

    #if !defined(FILE_B_H)
    #define      FILE_B_H
    
    template<class T> class B { /* ... */ };
    
    #endif
    

    Note that if the name of the class that is used in the friend declaration is not yet declared, it is forward declared on the spot (see http://en.cppreference.com/w/cpp/language/friend).

    Further details: