Search code examples
c++classtemplatesfriend

How to use friend keyword for template class


lets say that I have 2 template classes, A and B. If I want to make B a friend of A, what would I say ?

class<template T>
class A
{
public:
friend class B<T>; // ???


};

class<template T>
class B
{

};

Solution

  • To use a symbol, it must be declared or defined, this is the same in template. You need to forward declare template B. Also your syntax(class<template T>) to declare template class is not valid, it should be template <class T>.

    This should work:

    template <typename T>  // typename can be replaced with class 
    class B;
    
    template <typename T>
    class A
    {
    public:
    friend class B<T>;  
    };
    
    template <typename T>
    class B
    {
    
    };