Skip to content

Instantly share code, notes, and snippets.

@vladiant
Created April 8, 2025 18:00
Show Gist options
  • Save vladiant/73b4503513e6627716ccc7070e4dce2e to your computer and use it in GitHub Desktop.
Save vladiant/73b4503513e6627716ccc7070e4dce2e to your computer and use it in GitHub Desktop.
Tiny C++ template metaprogramming helpers
// https://vawale.github.io/posts/template_metaprogramming_helpers/
template<typename... Args>
consteval auto count() {
return sizeof...(Args);
}
template<template <typename T> typename Predicate, typename... Args>
consteval auto count_if() -> size_t {
return (0 + ... + Predicate<Args>{}());
}
template<typename T>
struct is_signed_type {
consteval bool operator ()() const {
return std::is_signed_v<T>;
}
};
template<template <typename T> typename Predicate, typename... Args>
consteval auto all_of() -> bool {
return (Predicate<Args>{}() && ...);
}
template<template <typename T> typename Predicate, typename... Args>
consteval auto any_of() -> bool {
return (Predicate<Args>{}() || ...);
}
template<template <typename T> typename Predicate, typename... Args>
consteval auto none_of() -> bool {
return !any_of<Predicate, Args...>();
}
template<template <typename T> typename Func, typename... Args>
consteval void for_each() {
(Func<Args>{}(), ...);
}
template<typename T>
struct assert_arithmetic {
consteval void operator ()() const {
static_assert(std::is_arithmetic_v<T>, "T must be arithmetic type");
}
};
template<template <typename T> typename Func, typename... Args>
consteval void for_each_tuple_type(std::tuple<Args...>) {
(Func<Args>{}(), ...);
}
template<template <typename T> typename Func, template Tuple>
consteval void for_each_tuple_type() {
auto evaluator = []<typename Tuple, template <typename T> typename Func, size_t... I>(std::index_sequence<I...>) {
(Func<std::tuple_element_t<I, Tuple>>{}(), ...);
};
evaluator.template operator() <Tuple, Func>
(std::make_index_sequence<std::tuple_size_v<Tuple>>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment