From a34183fb73d6cc62e68863647288165ee1d665e5 Mon Sep 17 00:00:00 2001 From: Alfi Maulana Date: Tue, 26 Dec 2023 13:49:19 +0700 Subject: [PATCH] feat: add boolean operator (#98) * feat: add `Error::operator bool()` operator * fix: mark `Error::operator bool` as explicit --- include/errors/error.hpp | 17 +++++++++++++++++ src/error.cpp | 4 ++++ test/error_test.cpp | 5 +++++ 3 files changed, 26 insertions(+) diff --git a/include/errors/error.hpp b/include/errors/error.hpp index ea42138..55006d7 100644 --- a/include/errors/error.hpp +++ b/include/errors/error.hpp @@ -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); /** diff --git a/src/error.cpp b/src/error.cpp index 44d040f..a7bb996 100644 --- a/src/error.cpp +++ b/src/error.cpp @@ -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(); } diff --git a/test/error_test.cpp b/test/error_test.cpp index c83e8f5..cbfb3e6 100644 --- a/test/error_test.cpp +++ b/test/error_test.cpp @@ -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;