0

Well, I'm trying to implement the copy_and_swap idiom on my first Stack in C++, for that I need to create a swap function and this swap function needs to be a friend function, I tried to do it by this way:

template <class T>
class Stack {
    private:
        int top;
        T* a;
        int MAX;

    public:
        Stack(int MAX);
        Stack(Stack<T>& s);
        bool push(T x);
        bool pop();
        T peek();
        bool isEmpty();
        friend void swap(Stack<T>& f, Stack<T>& s);
        ~Stack();
};

template <class T>
void Stack<T>::swap(Stack<T>& f, Stack<T>& s){
//I will put something where yet.
}

But, the VSCode says this about the swap function: class model "Stack " does not have a "swap" member (I translate for English, my VSCode runs in Portuguese).

How I can do that without receiving this error?

FUNKYBAT
  • 71
  • 1
  • 1
  • 8

1 Answers1

1

Your friend function is not template, so to define outside, you would have to define the non template function for each type (which seems impracticable):

void swap(Stack<int>& lhs, Stack<int>& rhs){/*..*/}
void swap(Stack<char>& lhs, Stack<char>& rhs){/*..*/}
void swap(Stack<MyType>& lhs, Stack<MyType>& rhs){/*..*/}

Simpler (and better IMO) is to define inside the class.

template <class T>
class Stack {
// ...
    friend void swap(Stack& lhs, Stack& rhs) { /*..*/ };
};

Alternative is to make the friend function template:

template <class T> class Stack;
template <class T> void swap(Stack<T>&, Stack<T>&);

template <class T>
class Stack {
// ...
    friend void swap<>(Stack& f, Stack& s); // Only the specialization is friend
};

template <class T>
void swap(Stack<T>& lhs, Stack<T>& rhs){ /**/ }
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Thanks for the answer, this works. But Im having a little problem to understand how the C++ compiler gonna understand that, how he know that void swap belongs to Stack without "Stack::"? – FUNKYBAT Apr 03 '20 at 21:02
  • I like to implement the functions outside of class, my problem was about how to do it outside, inside is easy to do it (as you said). – FUNKYBAT Apr 03 '20 at 21:07
  • 1
    friend functions don't belong to the class, so no `Stack::`. – Jarod42 Apr 03 '20 at 21:11
  • The "template class Stack;" in beggining is really necessary? If it is, what does it do in this code? VSCode didn't show any error without him. – FUNKYBAT Apr 03 '20 at 21:18
  • And sorry for the quantitive of questions. – FUNKYBAT Apr 03 '20 at 21:19
  • 1
    It is a (forward) declaration, needed to declare the `swap` function, which should be declared before the class to allow that friend declaration. – Jarod42 Apr 03 '20 at 21:21