Last active
December 15, 2021 15:44
-
-
Save dyigitpolat/e1f8bef207313ee7e1bf58cb71b1c1f7 to your computer and use it in GitHub Desktop.
bounded arithmetic demo
This file contains hidden or 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
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