2

For an assignment, I need to be able to make a templated friend class, I have the rest of the program working, but I cannot move past the errors. I am giving my code for the definition of the two classes as well as a photo of the errors. If I need to be more specific for my question, please tell me, but I honestly know slim to none about templates. Thank you.

    template<class T>
class Node{
        friend class NodeStack;
        public:
                Node();
                Node(const T & data, Node<T> * next = NULL);
                T & data();
                const T & data() const;

        public:
                Node<T> * m_next;
                T m_data;
};



template<class T>
class NodeStack{

template<class U>
friend std::ostream & operator<< (std::ostream & os, const NodeStack<T> & nodeStack);

public:
        NodeStack();
        NodeStack(size_t count, const T & value = T() );
        NodeStack(const NodeStack<T> &other);
        ~NodeStack();

        NodeStack<T> & operator=(const NodeStack<T> & rhs);

        T & top();
        const T & top() const;

        void push(const T & value);
        void pop();

        size_t size() const;
        bool empty() const;
        bool full() const;
        void clear();
        void serialize(std::ostream & os) const;

private:
        Node<T>* m_top;
};

2 Answers2

1

Changing your friend declaration to

friend class NodeStack<T>; 

should do the trick I think.

Arun
  • 3,138
  • 4
  • 30
  • 41
0

Template in C++ provides a specification for generating classes based on parameters. A class template is instantiated by passing a given set of types to it as template arguments.

So, class NodeStack doesn't exist until you instantiate with a template parameter.

Try:

friend class NodeStack<T>;

However, if you want to instantiate NodeStack with template parameter other than T, then you can use it as well.

For example, if you want to use int as template parameter:

friend class NodeStack<int>;

However, you need to forward declare your template class before Node class!

template <typename T>
class NodeStack;
abhiarora
  • 9,743
  • 5
  • 32
  • 57