Last active
December 16, 2022 18:33
-
-
Save aprotyas/02803a4ade50059285ec8f7badbf2edd to your computer and use it in GitHub Desktop.
Non-negative signed integer type (C++14)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <cstdint> | |
#include <stdexcept> | |
#include <type_traits> | |
template< | |
class T, | |
typename = std::enable_if_t<std::is_integral_v<T> && std::is_signed_v<T>> | |
> | |
class non_negative { | |
public: | |
// Can't be a valid default construction, I think (?) | |
non_negative() = delete; | |
non_negative(T _number) { | |
if (_number < static_cast<T>(0)) { | |
throw std::runtime_error("Please enter non-negative number."); | |
} | |
number = _number; | |
} | |
// Implicit conversion to underlying integral type | |
inline operator T() const { return static_cast<T>(number); } | |
private: | |
T number; | |
}; | |
/* | |
// Example use | |
void foo(int64_t cant_be_negative); | |
non_negative<int64_t> num = INT64_C(5); | |
foo(num); // implicitly convert to | |
// compile error | |
non_negative<double> num = 5.; | |
// runtime error | |
non_negative<int64_t> num = -5; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment