Skip to content

Instantly share code, notes, and snippets.

@gregzanch
Created November 10, 2025 21:29
Show Gist options
  • Select an option

  • Save gregzanch/4c313d960ae4ec7bf176b98cb2f7fbe1 to your computer and use it in GitHub Desktop.

Select an option

Save gregzanch/4c313d960ae4ec7bf176b98cb2f7fbe1 to your computer and use it in GitHub Desktop.
Small `within` command using concepts
#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