Rrobinvip
Rrobinvip

Reputation: 119

I want to implement a swap method in my class using templated swap

I have a class with only one member which is a vector.

class myClass{
private:
    vector<double> vector_member;
public:
    method1();
    method2();
    ...
}

I want to implement a swap method in this class with a templated swap. I'm learning the copy-swap idiom right now, the use of the swap method is to help with the operator =. What I want to achieve is something like this:

void Polynomial :: swap(Polynomial& p){
    std::swap(this.vector_member, p.vector_member)
}

I read about "swap" at here, swap Cplusplus.com, at the beginning it says: The behavior of this function template std::swap is equivalent to:

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}

But why can't I use it in my method? Or am I misunderstanding anything here?

Upvotes: 0

Views: 87

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596582

You are likely missing an #include for the header file that std::swap() is defined in.

Prior to C++11, std::swap() is in <algorithm>. In C++11 and later, it is in <utility> instead.

#include <utility> // or <algorithm>

void Polynomial :: swap(Polynomial& p){
    std::swap(vector_member, p.vector_member);
}

That being said, std::vector has its own swap() method. std::swap() is simply specialized for std::vector to call std::vector::swap(), so you can just call it directly yourself and not use std::swap at all:

void Polynomial::swap(Polynomial& p){
    vector_member.swap(p.vector_member);
}

Upvotes: 1

Related Questions