SlHelpers
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 
9 namespace SlHelpers {
10 
14 template<typename... More>
16  using Tuple = std::tuple<More...>;
17 public:
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  }
37 protected:
39  void resetMembers() noexcept {
40  std::apply([](auto &... args) { ((args = {}), ...); }, m_members);
41  }
42 private:
43  Tuple m_members;
44 };
45 
51 template<typename... More>
52 class LastErrorStr : public LastErrorBase<More...> {
53 public:
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 
77 private:
78  std::string m_lastError;
79 };
80 
86 template<typename... More>
87 class LastErrorStream : public LastErrorBase<More...> {
88 public:
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 
114 private:
115  std::ostringstream m_lastError;
116 };
117 
118 }
Stores a string (usually an error string) to be retrieved later.
Definition: LastError.h:87
LastErrorStream & reset() noexcept
Wipe out everything.
Definition: LastError.h:90
void resetMembers() noexcept
Wipe out members.
Definition: LastError.h:39
const std::string & lastError() const &noexcept
Obtain the stored string.
Definition: LastError.h:75
Stores a string (usually an error string) to be retrieved later.
Definition: LastError.h:52
LastErrorStream & operator<<(const T &x)
Store something into this error.
Definition: LastError.h:103
LastErrorStr & reset() noexcept
Wipe out everything.
Definition: LastError.h:55
std::string lastError() const noexcept
Obtain the stored string.
Definition: LastError.h:112
A base class for LastErrorStr and LastErrorStream.
Definition: LastError.h:15
void setError(T &&str) requires(std
Store a string into this error.
Definition: LastError.h:66
Definition: Color.h:8