Created
November 10, 2025 21:29
-
-
Save gregzanch/4c313d960ae4ec7bf176b98cb2f7fbe1 to your computer and use it in GitHub Desktop.
Small `within` command using concepts
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
| #pragma once | |
| #include <type_traits> | |
| template<typename NumericType> | |
| concept Numeric = std::is_arithmetic<NumericType>::value; | |
| constexpr uint8_t EXCLUSIVE = 0b00; | |
| constexpr uint8_t RIGHT_INCLUSIVE = 0b01; | |
| constexpr uint8_t LEFT_INCLUSIVE = 0b10; | |
| constexpr uint8_t BOTH_INCLUSIVE = 0b11; | |
| template<Numeric T> | |
| bool within(T value, T lower, T upper, uint8_t inclusivity = EXCLUSIVE) { | |
| // inclusivity bit pattern: | |
| // 0b00 -> (lower, upper) | |
| // 0b01 -> (lower, upper] | |
| // 0b10 -> [lower, upper) | |
| // 0b11 -> [lower, upper] | |
| bool lower_inclusive = inclusivity & 0b10; | |
| bool upper_inclusive = inclusivity & 0b01; | |
| bool lower_ok = lower_inclusive ? value >= lower : value > lower; | |
| bool upper_ok = upper_inclusive ? value <= upper : value < upper; | |
| return lower_ok && upper_ok; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment