【发布时间】:2019-09-22 08:40:20
【问题描述】:
计算机科学中有 2 个难题:缓存失效、命名事物和非一错误。
这是关于第二个问题:命名。
我正在寻找这种技术或类型是否已经在其他地方使用过并且有名称。 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 是真假之间的变体。它的运行时表示是0 或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++ 社区)中都广为人知的名称,甚至是描述“获取运行时值并在生成的代码中创建开关和一组编译时间值以供选择的动词” "胜过一句话。
一个好的答案将包括名称、描述该名称含义的引用/引用、在其他上下文中使用的该命名事物的示例,以及该名称等同于或包含上述类型/值和功能的证据.
(找到一个名称可能会有所帮助,它的概括将是 enum 而不是 bool,它具有固定数量的已知状态,以及将运行时值转换为每个 case 子句中的编译时常量。)
【问题讨论】:
-
我正试图了解这实际上是做什么的。它基本上是围绕
bool b = ...; if (b) func<true>(...); else func<false>(...);之类的包装吗? (但对于多个布尔值的所有组合) -
@NicolBolas 他们有一个
constexpr operator bool,它不依赖于在编译时评估的*this的constexprness。因此,虽然x不是 constexpr 值,但static_cast<bool>(x)是 常量表达式,这就是将它传递给模板的作用。它适用于当前所有主要的编译器;不是在一些旧的。 -
@André 是的,但这似乎是个坏主意。不,似乎不是。是。这是个坏主意。 (并且编译器在实践中到达那里之前会窒息)。而且一般有
2^32不同的32位整数,没有-1。但是,是的,类似的技术可以轻松地从O(n)代码创建O(2^n)程序集;除了小的n,不建议这样做。但这是一个次要问题;我正在寻找一个已在其他地方使用过的 name。 -
我会说 dispatcher,即使可能过于笼统。
-
我以前听说过在这种情况下使用“提升”。将运行时值提升为类型。