aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/util/OptionalRef.hpp
blob: e603a25eaebb040051e01ffbb22f6c31837005b1 (plain)
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
#pragma once

#include <stdexcept>

#include "OptionalRef.h"

namespace crepe {

template <typename T>
OptionalRef<T>::OptionalRef(T & ref) {
	this->set(ref);
}

template <typename T>
OptionalRef<T>::OptionalRef(const OptionalRef<T> & other) {
	this->ref = other.ref;
}

template <typename T>
OptionalRef<T>::OptionalRef(OptionalRef<T> && other) {
	this->ref = other.ref;
	other.clear();
}

template <typename T>
OptionalRef<T> & OptionalRef<T>::operator=(const OptionalRef<T> & other) {
	this->ref = other.ref;
	return *this;
}

template <typename T>
OptionalRef<T> & OptionalRef<T>::operator=(OptionalRef<T> && other) {
	this->ref = other.ref;
	other.clear();
	return *this;
}

template <typename T>
T & OptionalRef<T>::get() const {
	if (this->ref == nullptr)
		throw std::runtime_error("OptionalRef: attempt to dereference nullptr");
	return *this->ref;
}

template <typename T>
void OptionalRef<T>::set(T & ref) noexcept {
	this->ref = &ref;
}

template <typename T>
void OptionalRef<T>::clear() noexcept {
	this->ref = nullptr;
}

template <typename T>
OptionalRef<T> & OptionalRef<T>::operator=(T & ref) {
	this->set(ref);
	return *this;
}

template <typename T>
OptionalRef<T>::operator bool() const noexcept {
	return this->ref == nullptr;
}

}