aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/util/Private.h
blob: d725a5ebb9a3c95c630b7bfe5d8390a2f64910e0 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#pragma once

#include <functional>
#include <typeindex>

namespace crepe {

/**
 * \brief Utility for storing type hidden from user
 *
 * This class can be used to store types which cannot be used in the API directly due to header
 * distribution limitations. This class is similar to `std::any`, but provides a method for
 * retrieving a mutable reference to the stored object.
 */
class Private {
public:
	Private() = default;
	~Private();
	/**
	 * \name Copy
	 *
	 * \note These functions do not do anything, resulting in `*this` being an empty (default)
	 * instance.
	 *
	 * \{
	 */
	Private(const Private &);
	Private & operator=(const Private &);
	//! \}
	/**
	 * \name Move
	 *
	 * These functions actually move the stored type if present.
	 *
	 * \{
	 */
	Private(Private &&);
	Private & operator=(Private &&);
	//! \}

	/**
	 * \brief Get the stored object
	 *
	 * \tparam T Type of stored object
	 *
	 * \returns Mutable reference to stored object
	 *
	 * \throws std::out_of_range if this instance does not contain any object
	 * \throws std::logic_error if the stored type and requested type differ
	 */
	template <typename T>
	T & get() const;

	/**
	 * \brief Create and store an arbitrary object
	 *
	 * \tparam T Type of object
	 * \tparam Args Perfect forwarding arguments
	 * \param args Perfect forwarding arguments
	 *
	 * All arguments to this function are forwarded using `std::forward` to the constructor of T.
	 *
	 * \returns Mutable reference to stored object
	 *
	 * \note If this instance already contained an object, this function implicitly destroys the
	 * previous object.
	 */
	template <typename T, typename... Args>
	T & set(Args &&... args);

	/**
	 * \brief Check if this instance contains an object
	 *
	 * \returns `true` if this instance is empty, `false` if it contains an object
	 */
	bool empty() const noexcept;

private:
	//! Wrapper for destructor call of stored object type
	std::function<void(void *)> destructor;
	//! Stored object's type
	std::type_index type = typeid(void);
	//! Stored object
	void * instance = nullptr;
};

} // namespace crepe

#include "Private.hpp"