asserts.h
Go to the documentation of this file.
1 
24 #ifndef FCPP_VALIDATIONS_H
25 #define FCPP_VALIDATIONS_H
26 
27 #include <sstream>
28 #include <string>
29 
30 namespace fcpp::asserts {
31 
37 class invariant {
38 private:
39  const bool condition_;
40  std::stringstream message_;
41 
42  invariant(bool condition, std::string message)
43  : condition_(condition), message_(message) {}
44 
45  // https://herbsutter.com/2014/05/03/reader-qa-how-can-i-prevent-a-type-from-being-instantiated-on-the-stack/
46  invariant() = delete;
47  invariant(const invariant &) = default;
48 
49 public:
50  ~invariant() noexcept(false) {
51  if (!condition_) {
52  // Living dangerously, guaranteed not to live on the stack though. See
53  // above link.
54  throw std::invalid_argument( // lgtm [cpp/throw-in-destructor]
55  message_.str());
56  }
57  }
58 
67  template <typename Text>
68  friend invariant &&operator<<(invariant &&item, const Text &text) {
69  item.message_ << text;
70  return std::move(item);
71  }
72 
82  static invariant eval(bool condition) { return invariant(condition, ""); }
83 };
84 
85 } // namespace fcpp::asserts
86 
87 #endif // FCPP_VALIDATIONS_H
friend invariant && operator<<(invariant &&item, const Text &text)
Sets the message as an incoming stream.
Definition: asserts.h:68
Enforce assertions that a condition will never change during the running lifetime of that code.
Definition: asserts.h:37
static invariant eval(bool condition)
Evaluate the invariant and throw std::invalid_argument if violated.
Definition: asserts.h:82