Skip to content

Commit

Permalink
feat: add boolean operator (#98)
Browse files Browse the repository at this point in the history
* feat: add `Error::operator bool()` operator

* fix: mark `Error::operator bool` as explicit
  • Loading branch information
threeal authored Dec 26, 2023
1 parent 6bcb1bc commit a34183f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
17 changes: 17 additions & 0 deletions include/errors/error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,23 @@ class Error {
*/
std::string_view message() const;

/**
* @brief Checks whether the object contains an error.
* @return `true` if it contains an error, otherwise `false`.
*
* @code{.cpp}
* const auto err = errors::make("unknown error");
*
* // Print "contains error".
* if (err) {
* std::cout << "contains error" << std::endl;
* } else {
* std::cout << "no error" << std::endl;
* }
* @endcode
*/
explicit operator bool() const;

friend Error make(const std::string& msg);

/**
Expand Down
4 changes: 4 additions & 0 deletions src/error.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ std::string_view Error::message() const {
return *message_ptr;
}

Error::operator bool() const {
return (bool)message_ptr;
}

std::ostream& operator<<(std::ostream& os, const errors::Error& err) {
return os << "error: " << err.message();
}
Expand Down
5 changes: 5 additions & 0 deletions test/error_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ TEST_CASE("Error Construction") {
REQUIRE(err.message() == "unknown error");
}

TEST_CASE("Error Checking") {
const auto err = errors::make("unknown error");
REQUIRE(err);
}

TEST_CASE("Error Printing Using OStream") {
const auto err = errors::make("unknown error");
const auto ss = std::stringstream() << err;
Expand Down

0 comments on commit a34183f

Please sign in to comment.