diff options
author | Sven Göthel <[email protected]> | 2024-09-14 06:08:32 +0200 |
---|---|---|
committer | Sven Göthel <[email protected]> | 2024-09-14 06:08:32 +0200 |
commit | b8f7f12979bc35d7cab0905ae83040847721c86a (patch) | |
tree | 9c9cd3b4131d63c0b3f08d5d10b56004971a5dc4 | |
parent | 78f10abbcfcbd4e876b3d34bc06cbd4baccc8d11 (diff) |
Add scoped enum Bool as a bool alternative w/o dangerous implicit conversion
-rw-r--r-- | include/jau/cpp_lang_util.hpp | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/include/jau/cpp_lang_util.hpp b/include/jau/cpp_lang_util.hpp index 7b3726a..e29bf6e 100644 --- a/include/jau/cpp_lang_util.hpp +++ b/include/jau/cpp_lang_util.hpp @@ -29,6 +29,7 @@ #include <typeinfo> #include <string> #include <cstring> +#include <ostream> namespace jau { @@ -844,6 +845,64 @@ namespace jau { f(); } + enum class Bool : bool { + False = false, + True = true + }; + constexpr Bool True() noexcept { return Bool::True; } + constexpr Bool False() noexcept { return Bool::False; } + + constexpr bool value(const Bool rhs) noexcept { + return static_cast<bool>(rhs); + } + constexpr Bool operator!(const Bool rhs) noexcept { + return static_cast<Bool>(!value(rhs)); + } + constexpr Bool operator&&(const Bool lhs, const Bool rhs) noexcept { + return static_cast<Bool>(value(lhs) && value(rhs)); + } + constexpr Bool operator||(const Bool lhs, const Bool rhs) noexcept { + return static_cast<Bool>(value(lhs) || value(rhs)); + } + constexpr Bool operator^(const Bool lhs, const Bool rhs) noexcept { + return static_cast<Bool>(value(lhs) ^ value(rhs)); + } + constexpr Bool operator|(const Bool lhs, const Bool rhs) noexcept { + return static_cast<Bool>(value(lhs) || value(rhs)); + } + constexpr Bool operator&(const Bool lhs, const Bool rhs) noexcept { + return static_cast<Bool>(value(lhs) && value(rhs)); + } + constexpr Bool& operator|=(Bool& lhs, const Bool rhs) noexcept { + lhs = lhs | rhs; + return lhs; + } + constexpr Bool& operator&=(Bool& lhs, const Bool rhs) noexcept { + lhs = lhs & rhs; + return lhs; + } + constexpr Bool& operator^=(Bool& lhs, const Bool rhs) noexcept { + lhs = lhs ^ rhs; + return lhs; + } + constexpr bool operator==(const Bool lhs, const Bool rhs) noexcept { + return value(lhs) == value(rhs); + } + constexpr bool operator!=(const Bool lhs, const Bool rhs) noexcept { + return !(lhs == rhs); + } + constexpr const char* to_string(const Bool v) noexcept { + if( value(v) ) { + return "true"; + } else { + return "false"; + } + } + inline std::ostream & operator << (std::ostream &out, const Bool c) { + out << to_string(c); + return out; + } + /**@}*/ } // namespace jau |