Skip to content

Instantly share code, notes, and snippets.

@dyigitpolat
Last active December 2, 2021 08:02
Show Gist options
  • Save dyigitpolat/38f778bbec5e4fcfd421d62f9bb1406d to your computer and use it in GitHub Desktop.
Save dyigitpolat/38f778bbec5e4fcfd421d62f9bb1406d to your computer and use it in GitHub Desktop.
compile time bounds checking proof of concept
template<long MIN, long MAX>
struct BoundedInteger
{
BoundedInteger()
{
value_ = MIN;
}
BoundedInteger(long value)
{
if (value < MIN) value = MIN;
if (value > MAX) value = MAX;
value_ = value;
}
operator long&() { return value_; }
long value_{};
static constexpr long MIN_VAL = MIN;
static constexpr long MAX_VAL = MAX;
};
template<long I>
using ConstantInteger = BoundedInteger<I,I>;
template<long MIN_L, long MAX_L, long MIN_R, long MAX_R>
auto operator+(
BoundedInteger<MIN_L, MAX_L> left,
BoundedInteger<MIN_R, MAX_R> right)
-> BoundedInteger<MIN_L + MIN_R, MAX_R + MAX_L>
{
return left.value_ + right.value_;
}
#include <iostream>
int main()
{
BoundedInteger<30, 45> ival{};
std::cin >> ival;
auto result = ConstantInteger<5>{} + ival;
static_assert(result.MAX_VAL <= 50);
static_assert(result.MIN_VAL >= 35);
std::cout << result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment