I would like to swap two arrays of ints of some fixed size.
Counterintuitively, the following does not compile because no matching instance of swap has been found.
#include <array>
#include <utility>
int main()
{
std::array<int,3> a, b;
std::swap< std::array<int,3> >( a, b );
return 0;
}
I find this surprising. However, replacing the swap with std::swap(a,b) compiles and (according to VSCode) has signature
inline void std::swap<int, 3UL>(std::array<int, 3UL> &__one, std::array<int, 3UL> &__two)
which I cannot make sense of either.
Q: What is going on here?
The overload you are looking for is (from cppreference):
template< class T, std::size_t N > constexpr void swap( std::array<T, N>& lhs, std::array<T, N>& rhs ) noexcept(/* see below */);
As the error reports, the compiler can't find a viable overload of std::swap() that matches std::swap<std::array<int,3>>.
This would be the "right" way to supply template arguments explictly:
#include <array>
#include <utility>
int main()
{
std::array<int,3> a, b;
std::swap<int,3>( a, b );
return 0;
}
I doubt there is a situation where you actually want to do that though.
PS: You can also see that in the signature you get from VSCOde: std::swap<int, 3UL> is not std::swap<std::array<int,3UL>>. However, looking at implementation can be misleading sometimes and I rather suggest to consult documentation first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With