-1

code of my two template class Errors

Ive tried using "friend class" declaration instead of "friend". replacing "friend" with "friend class"

The errors is caused by creating a Mydeque object within main.

template <typename T>
class Mydeque 
{
    private:
        T* data;
        int cap, sz;
        friend class Iterator<T>;

    public:
        Mydeque(): cap(0), sz(0)  //Constructor
        {
            //do nothing
        }

};

template<class T>
class Iterator
{
    public:
        

    private:
        size_t current;
        Mydeque<T>* container;
        friend class Mydeque<T>;
};
hobo
  • 1
  • 1
  • 1
    The question is WHY would you need them to be friends both ways? I can imagine you want to give the iterator access to the internals of the container... but the other way around? – Pepijn Kramer Feb 09 '23 at 08:16
  • Can you add the code and errors as text? See [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/q/285551/2752075) – HolyBlackCat Feb 09 '23 at 08:16
  • Idk the homework strictly stated I had to. It said "The Mydeque class is templated by a type T that has a friend Iterator class template" and another part saying "make Mydeque i a friend of Iterator" – hobo Feb 09 '23 at 08:19
  • you need to forward declare `Iterator` https://godbolt.org/z/T66feqWEx – Alan Birtles Feb 09 '23 at 08:25

1 Answers1

0

You can either forward declare the class template and then befriend it or add a separate template clause as shown below:

//forward declaration
template<typename T> class Iterator;

template <typename T>
class Mydeque 
{
    private:
        friend class Iterator<T>;

};

template<class T>
class Iterator
{
        friend class Mydeque<T>;
};

demo

Method 2

In this case, instead of forward declaring the befriend class template separaterly, we add a separate template clause so that all instantiations of that template are friends.

template <typename T>
class Mydeque 
{
   
        template<typename U> friend  class Iterator;

};

template<class T>
class Iterator
{
        friend class Mydeque<T>;
};
Jason
  • 36,170
  • 5
  • 26
  • 60
  • I tried that before but it didnt work. – hobo Feb 09 '23 at 08:28
  • "template friend class Iterator;" instead of " friend class Iterator;" was what fixed it for me. – hobo Feb 09 '23 at 08:29
  • oh nvm it worked, i just typed it wrong :/ Do you know the difference between what I did and what you did? – hobo Feb 09 '23 at 08:30
  • @hobo See method 2 in my updated answer where i've explained what happen in case `"template friend class Iterator;` – Jason Feb 09 '23 at 08:42