SlHelpers
Loading...
Searching...
No Matches
LastError.h
1// SPDX-License-Identifier: GPL-2.0-only
2
3#pragma once
4
5#include <string>
6#include <sstream>
7#include <tuple>
8
9namespace SlHelpers {
10
14template<typename... More>
15class LastErrorBase {
16 using Tuple = std::tuple<More...>;
17public:
18 LastErrorBase() noexcept {}
19
21 template<size_t idx>
22 std::tuple_element_t<idx, Tuple> &get() noexcept {
23 return std::get<idx>(m_members);
24 }
25
27 template<size_t idx>
28 const std::tuple_element_t<idx, Tuple> &get() const noexcept {
29 return std::get<idx>(m_members);
30 }
31
33 template<size_t idx, typename Arg>
34 void set(Arg &&val) noexcept {
35 std::get<idx>(m_members) = std::forward<Arg>(val);
36 }
37protected:
39 void resetMembers() noexcept {
40 std::apply([](auto &... args) { ((args = {}), ...); }, m_members);
41 }
42private:
43 Tuple m_members;
44};
45
51template<typename... More>
52class LastErrorStr : public LastErrorBase<More...> {
53public:
55 LastErrorStr &reset() noexcept {
56 m_lastError.clear();
57 this->resetMembers();
58 return *this;
59 }
60
65 template <typename T>
66 void setError(T &&str)
67 requires (std::is_convertible_v<T, std::string_view>) {
68 m_lastError = std::forward<T>(str);
69 }
70
75 const std::string &lastError() const & noexcept { return m_lastError; }
76
77private:
78 std::string m_lastError;
79};
80
86template<typename... More>
87class LastErrorStream : public LastErrorBase<More...> {
88public:
90 LastErrorStream &reset() noexcept {
91 m_lastError.str({});
92 m_lastError.clear();
93 this->resetMembers();
94 return *this;
95 }
96
102 template<typename T>
104 m_lastError << x;
105 return *this;
106 }
107
112 std::string lastError() const noexcept { return m_lastError.str(); }
113
114private:
115 std::ostringstream m_lastError;
116};
117
118}
void resetMembers() noexcept
Wipe out members.
Definition LastError.h:39
void set(Arg &&val) noexcept
Set n-th error member.
Definition LastError.h:34
std::tuple_element_t< idx, Tuple > & get() noexcept
Get n-th error member.
Definition LastError.h:22
const std::tuple_element_t< idx, Tuple > & get() const noexcept
Get n-th error member.
Definition LastError.h:28
Stores a string (usually an error string) to be retrieved later.
Definition LastError.h:52
const std::string & lastError() const &noexcept
Obtain the stored string.
Definition LastError.h:75
void setError(T &&str)
Store a string into this error.
Definition LastError.h:66
LastErrorStr & reset() noexcept
Wipe out everything.
Definition LastError.h:55
Stores a string (usually an error string) to be retrieved later.
Definition LastError.h:87
std::string lastError() const noexcept
Obtain the stored string.
Definition LastError.h:112
LastErrorStream & reset() noexcept
Wipe out everything.
Definition LastError.h:90
LastErrorStream & operator<<(const T &x)
Store something into this error.
Definition LastError.h:103