Skip to content

Instantly share code, notes, and snippets.

@aprotyas
Last active December 16, 2022 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aprotyas/02803a4ade50059285ec8f7badbf2edd to your computer and use it in GitHub Desktop.
Save aprotyas/02803a4ade50059285ec8f7badbf2edd to your computer and use it in GitHub Desktop.
Non-negative signed integer type (C++14)
#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