Background:
I am trying to implement a function, let's call it mysort
, that takes variable number of arguments of same type and sort them. For example the code below should print 1 2 3
template <typename ... Args>
void mysort(Args& ... args);
int main(int, char**)
{
int x = 3;
int y = 1;
int z = 2;
mysort(x, y, z);
cout << x << ' ' << y << ' ' << z << endl;
return 0;
}
What I have tried:
Here is the solution I came up with
#include <array>
#include <algorithm>
#include <functional>
template <typename T, typename ... Args>
void mysort(T& t, Args& ... args)
{
constexpr size_t n = sizeof...(Args) + 1;
std::array<std::reference_wrapper<T>, n> temp = { std::ref(t), std::ref(args)... };
std::sort(temp.begin(), temp.end());
}
But this solution doesn't work because what std::swap
does with std::reference_wrapper
is not what I expect (I expect any changes to std::reference_wrapper
should change the object for which std::reference_wrapper
was created).
Everything starts working after adding
namespace std
{
void swap(std::reference_wrapper<int>& a, std::reference_wrapper<int>& b) noexcept
{
std::swap(a.get(), b.get());
}
}
I'm not sure if the standard requires std::sort
to use std::swap
, so I think this is not a complete solution and is implementation-dependent.
Summarizing:
My idea of a std::reference_wrapper is that it should behave just like a reference, but that doesn't seem to be the case. Here are my questions:
- What is the best way to implement
mysort
? - Why doesn't the standard provide a
std::swap
specification forstd::reference_wrapper
that would swap underlying objects?
Thank you in advance for your answers!