Skip to content

Instantly share code, notes, and snippets.

@dyigitpolat
Last active December 15, 2021 15:44
Show Gist options
  • Save dyigitpolat/e1f8bef207313ee7e1bf58cb71b1c1f7 to your computer and use it in GitHub Desktop.
Save dyigitpolat/e1f8bef207313ee7e1bf58cb71b1c1f7 to your computer and use it in GitHub Desktop.
bounded arithmetic demo
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_;
}
template <long BASE_MODIFIER>
struct Upgrade
{
BoundedInteger<0, 5> level{};
ConstantInteger<BASE_MODIFIER> base_modifier{};
auto get_modifier()
{
return base_modifier + level;
}
};
using BlueUpgrade = Upgrade<5>;
using RedUpgrade = Upgrade<10>;
template <typename Upgrade>
struct SilverWeapon
{
Upgrade upgrade;
ConstantInteger<20> base_damage{};
auto get_damage()
{
return base_damage + upgrade.get_modifier();
}
};
#include <iostream>
int main()
{
SilverWeapon<RedUpgrade> w1{4};
SilverWeapon<BlueUpgrade> w2{2};
constexpr long w1min = decltype(w1.get_damage())::MIN_VAL;
constexpr long w1max = decltype(w1.get_damage())::MAX_VAL;
constexpr long w2min = decltype(w2.get_damage())::MIN_VAL;
constexpr long w2max = decltype(w2.get_damage())::MAX_VAL;
std::cout << "w1 min: " << w1min << ", ";
std::cout << "w1 max: " << w1max << "\n";
std::cout << "w1 current: " << w1.get_damage() << "\n";
std::cout << "w2 min: " << w2min << ", ";
std::cout << "w2 max: " << w2max << "\n";
std::cout << "w1 current: " << w2.get_damage() << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment