-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_Utility.hpp
More file actions
59 lines (49 loc) · 1.51 KB
/
_Utility.hpp
File metadata and controls
59 lines (49 loc) · 1.51 KB
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
#include <memory>
#include <type_traits>
#include <utility>
// 1. 保存目标对象的当前值
// 2. 用新值替换目标对象的当前值
// 3. 返回保存的旧值
template <typename T, typename U = T>
T exchange(T &obj, U &&new_val) {
T old_val = std::move(obj);
obj = std::forward<U>(new_val);
return old_val;
}
template <typename T>
void swap(T &a, T &b) noexcept {
T temp = std::move(a);
a = std::move(b);
b = std::move(temp);
}
// 为什么要加remove_reference
// 防止传入左值推导为引用, T& && 折叠为T&
// remove reference 保证 T && 折叠为T&&
template <typename T>
std::remove_reference_t<T> &&move(T &&t) {
return static_cast<std::remove_reference_t<T> &>(t);
}
// 两个重载版本
// t是左值时,推导为T&, 调用版本1, T& && 折叠为T&
// t是右值时,推导为T, T && 折叠为T&&
template <typename T>
T &&forward(std::remove_reference_t<T> &t) {
return static_cast<T &&>(t);
}
template <typename T>
T &&forward(std::remove_reference_t<T> &&t) {
// 不知道有什么用
static_assert(!std::is_lvalue_reference<T>::value,
"std::forward must not be used to convert an rvalue to an lvalue");
return static_cast<T &&>(t);
}
template <typename T>
void PerfectForward(T &&t) {
f(forward<T>(t));
}
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args &&...args) {
// Args为空会退化为new T()
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
// std::make_unique/std::make_shared