There are 2 hard problems in computer science: cache invalidation, naming things and off-by-one errors.
This is about the 2nd problem: naming things.
I'm looking if this technique or type has been used somewhere else already and has a name. dichotomy
is an ok name, but bools_at_compile_time
is a horrible one.
using dichotomy_t = std::variant<std::false_type, std::true_type>;
// (or a struct that inherits from that, and overloads operator bool())
constexpr dichotomy_t dichotomy( bool b ) {
if (b) return std::true_type{};
return std::false_type{};
}
template<class F, class...Bools>
constexpr auto bools_at_compile_time( F&& f, Bools...bools ) {
static_assert( (std::is_same<Bools, bool>{} && ...) );
return std::visit( std::forward<F>(f), dichotomy(bools)... );
}
dichotomy_t
is a variant between true and false. Its runtime representation is 0
or 1
.
What this lets you do is:
auto foo( bool x, bool y ) { // <-- x and y are run-time bools here
auto func = [&](auto x, auto y) {
return some_template<x,y>(); // <-- x and y are compile-time bools here
};
return bools_at_compile_time( func, x, y ); // <-- converts runtime to compile time bools
}
Is there a name for dichotomy_t
or the more general bools_at_compile_time
technique? I'm looking for a name that is well known in any community (even a non-C++ one), even a verb that describes "taking a runtime value and creating a switch and a set of compile time value in generated code to pick between" better than a sentence.
A good answer would include the name, citations/quotes describing what that name means, examples of that named thing in use in the other context, and evidence that this name is equivalent to or inclusive of the above type/value and function.
(It may help to find a name the generalization of this would be an enum
instead of a bool
, which has a fixed number of known states, and a switch/case map that converts the runtime value into a compile-time constant in each case clause.)
bool b = ...; if (b) func<true>(...); else func<false>(...);
? (but for all combinations of values for multiple bools) – Rehabilitationconstexpr operator bool
that does not depend on theconstexpr
ness of*this
to be evaluated at compile time. So whilex
is not a constexpr value,static_cast<bool>(x)
is a constant expression, and that is what passing it to a template does. It works in all major current compilers; not in some older ones. – Ilex2^32
different 32 bit ints, no-1
. But yes, techniques similar to this can createO(2^n)
assembly fromO(n)
code easily; that is not advised for anything except smalln
. But that is a side issue; I'm looking for a name for this that has been used elsewhere. – Ilexvariant
that large. – Ongmeta
or something like that for meta-functions. I read theses articles but never found a hint about a general used keyword related to your question: C++ Core Guidelines: Programming at Compile Time with the Type-Traits and C++ Core Guidelines: Programming at Compile Time with the Type-Traits II – Bourke