Search code examples
c++classtemplatesfriend

Declaring a class template as a friend of a class template in C++


I'm trying to declare a class template as a friend of another class template, so the private members in one class can be accessed by the other. For example I have two classes as the following:

A.h
template <typename T>
class A {
    private:
       T content;
}

and

B.h
#include "A.h"
template <typename T>
class B {
    public:
        void add(T);

    private:
        A<T>* ptr;
}

Now, I want to make class B< T> a friend of class A< T>, so I can have access to class A< T>'s content through class B< T>'s function add. So, I added a few lines to A.h:

A.h
template <typename T> class B;
template <typename T> 
class A {
    friend class B<T>;
    ...

I'm using Visual Studio and the above code would give me "unresolved external symbol..." error (Error code LNK2019). I have tried other variations but I kept getting a linker error. Please help me out. Thank you.

The definitions for the function add(T) is in B.cpp which I didn't write in the post.


Solution

  • The following code builds fine on gcc. I added a definition of B<T>::add(T), as it was missing. It's very possible that the absence caused your link - not compilation! - error.

    template<typename T>
    class B;
    
    template <typename T>
    class A {
        private:
           T content;
    
        friend B<T>;
    };
    
    template <typename T>
    class B {
        public:
            void add(T t) { A<T> a; a.content = t; }
    
        private:
            A<T>* ptr;
    };
    
    int main() {
        A<int> a;
        B<int> b;
        b.add(3);
    }