-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.hpp
62 lines (49 loc) · 1.28 KB
/
default.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
#pragma once
#include <sps/optional>
namespace sps {
struct DefaultValue {};
static const DefaultValue defaultValue;
template<typename T>
using IsNotReference =
typename std::enable_if<!std::is_reference<T>::value, void>::type;
template<typename T, T... DefaultedParameter>
class Defaulted {
public:
// Do not make these explicit
Defaulted(T const& t) : value_(t) {}
template<typename T_ = T, typename = IsNotReference<T_>>
Defaulted(T&& t) : value_(std::move(t)) {}
Defaulted(DefaultValue) : value_(DefaultedParameter...) {}
T const& get_or_default() const {
return value_;
}
T & get_or_default() {
return value_;
}
private:
T value_;
};
template<typename T, typename GetDefaultValue>
class DefaultedF {
public:
DefaultedF(T const& t) : value_(t) {}
template<typename T_ = T, typename = IsNotReference<T_>>
DefaultedF(T&& t) : value_(std::move(t)) {}
DefaultedF(DefaultValue) : value_(sps::nullopt) {}
template<typename... Args>
T get_or_default(Args&&... args) {
if (value_) {
return *value_;
} else {
return GetDefaultValue::get(std::forward<Args>(args)...);
}
}
private:
sps::optional<T> value_;
};
} // namespace sps
/* Local variables: */
/* indent-tabs-mode: nil */
/* tab-width: 2 */
/* c-basic-offset: 2 */
/* End: */