3

I'm writing a custom class for which I want to use the std::swap function.

As I read in this post How to overload std::swap() , I have to overload it in the same namespace of the object I'm trying to swap and there's an example.

I (thing) I'm replicating the example, but the function that gets called when using std::swap() isn't the one defined by me.

Here is what my code looks alike:

//grid.hpp
namespace myname {
template <typename T>
class Grid
{
    ...
    friend void swap(Grid &a, Grid &b)
    {
        using std::swap;
        std::cout << "Custom Swap Used" << std::endl;
        swap(a.nrwow, b.nrows);
        swap(a.ncols, b.ncols);
        a.grid.swap(b.grid);
    }
}
}

but when I call the swap function no string gets printed, so this function doesn't get called.

//file.cpp
#include"../src/grid.hpp"

int main() {
myname::Grid<int> grid1(10, 10);
myname::Grid<int> grid2(10, 10);
std::swap(grid1, grid2); // this should print a string
}
linamamm
  • 65
  • 6

1 Answers1

4

You have to uses std::ranges::swap, or find it via ADL if you aren't using C++20:

myname::Grid<int> grid1(10, 10);
myname::Grid<int> grid2(10, 10);

std::ranges::swap(grid1, grid2);

// Or with ADL
using std::swap;
swap(grid1, grid2);

"Swapping" does not exactly mean std::swap, but this form of "using std::swap; swap(x, y);", which is encapsulated by std::ranges::swap.


Writing std::swap(grid1, grid2) directly calls the default template<typename T> void std::move(T&, T&);. This will use the move construct and move assignment operators instead of your custom swap function, which is why you don't see "Custom Swap Used".

Artyer
  • 31,034
  • 3
  • 47
  • 75