-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap.hpp
75 lines (63 loc) · 1.65 KB
/
swap.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#ifndef _NARY_SWAP_HPP_
#define _NARY_SWAP_HPP_
// Copyright (c) 2019-2020 Paul Keir, University of the West of Scotland.
// A version of std::swap which works for 0 or more variables using C++17 fold
// expressions. See https://pkeir.github.io/blog/2019/01/08/nary-swap/
#include <utility>
#include <type_traits>
namespace nary {
constexpr void swap() noexcept {}
template <typename T, typename ...Ts>
constexpr
std::enable_if_t<std::conjunction_v<std::is_same<T,Ts>...>>
swap(T &x, Ts &...xs)
noexcept (
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_move_assignable_v<T>
)
{
T tmp = std::move(x);
struct wrap {
constexpr wrap operator+(wrap &&w) { x = std::move(w.x); return w; }
T &x;
};
auto c = [](auto &...xs) { (... + wrap{xs}); };
c(x,xs...,tmp);
}
constexpr void swapr() noexcept {}
template <typename T> constexpr void swapr(T &) noexcept {}
template <typename T, typename ...Ts>
constexpr
std::enable_if_t<std::conjunction_v<std::is_same<T,Ts>...>>
swapr(T & x, Ts &...xs)
noexcept (
std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_move_assignable_v<T>
)
{
T tmp = std::move((xs , ...));
struct wrap {
constexpr wrap operator+(wrap &&w) { w.x = std::move(x); return *this; }
T &x;
};
auto c = [](auto &...xs) { (wrap{xs} + ...); };
c(tmp,x,xs...);
}
} // namespace nary
/*
template <typename T>
constexpr void swap(T &t1, T &t2)
{
T temp = std::move(t1);
t1 = std::move(t2);
t2 = std::move(temp);
}
template <typename T>
constexpr void swapr(T &t1, T &t2)
{
T temp = std::move(t2);
t2 = std::move(t1);
t1 = std::move(temp);
}
*/
#endif // _NARY_SWAP_HPP_