Skip to content

Instantly share code, notes, and snippets.

@reach2sayan
Last active February 6, 2025 21:56
Show Gist options
  • Save reach2sayan/b0b8d635279af311ea4eae186853ce6f to your computer and use it in GitHub Desktop.
Save reach2sayan/b0b8d635279af311ea4eae186853ce6f to your computer and use it in GitHub Desktop.
static_variant_pair
#include <type_traits>
#include <iostream>
template<typename T, T val>
struct binary_type {
using value_type = T;
static constexpr T value = val;
constexpr operator T() const noexcept { return value; }
constexpr T operator()() const noexcept { return value; }
};
template<typename T, T val>
using binary_type_t = binary_type<T, val>;
template<auto val>
using integral_constant = binary_type<decltype(val), val>;
using hg2g = binary_type<int, 42>;
constexpr int answer_to_everything = hg2g{}; // 42
constexpr int get_answer_to_everything = hg2g{}(); // 42
using double_pi = binary_type_t<double, 3.14>;
static_assert(double_pi::value == 3.14);
using my_char = integral_constant<'A'>;
enum class ExecutionContext { Dynamics, SteadyState };
using DynamicsContext = binary_type<ExecutionContext, ExecutionContext::Dynamics>;
using SteadyStateContext = binary_type<ExecutionContext, ExecutionContext::SteadyState>;
int func(int a, int b, DynamicsContext)
{
return a+b;
}
int func(int a, int b, SteadyStateContext)
{
return a*b;
}
int main()
{
static_assert(my_char::value == 'A');
static_assert(std::is_same_v<my_char::value_type, char>);
static_assert(hg2g::value == 42);
static_assert(std::is_same_v<hg2g::value_type, int>);
static_assert(DynamicsContext::value == ExecutionContext::Dynamics);
return func(1,2, SteadyStateContext{});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment