计算机科学中有两个难题:缓存失效、命名和差一错误。
这是关于第二个问题:命名事物。
我正在寻找这种技术或类型是否已经在其他地方使用过并且有一个名称。dichotomy
是一个不错的名字,但是bools_at_compile_time
是一个可怕的。
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
是 true 和 false 之间的变体。其运行时表示为0
or 1
.
这可以让你做的是:
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
}
有没有名字dichotomy_t
或者更一般的bools_at_compile_time
技术?我正在寻找一个在任何社区(甚至是非 C++ 社区)中都众所周知的名称,甚至是一个描述“获取运行时值并在生成的代码中创建一个开关和一组编译时值以在两者之间进行选择”的动词“比一句话更好。
实例 https://godbolt.org/z/5tD_iR
一个好的答案将包括名称、描述该名称含义的引文/引文、在其他上下文中使用该命名事物的示例,以及该名称等同于或包含上述类型/值和函数的证据。
(这可能有助于找到一个名称,概括起来就是enum
代替bool
,它具有固定数量的已知状态,以及将运行时值转换为每个 case 子句中的编译时常量的 switch/case 映射。)