我有一个任意 bool 值 OR
运行时函数any_run
#include <assert.h>
bool any_run() { return false; }
template <typename... B>
bool any_run(bool a, B... b)
{
assert(a);
return a || any_run(b...);
}
以及编译时类似物 any_comp
#include <type_traits>
template <bool E>
using expr = std::integral_constant <bool, E>;
using _true = expr <true>;
using _false = expr <false>;
template <typename... A>
struct any_comp : public _false { };
template <typename A, typename... B>
struct any_comp <A, B...> : public expr <A() || any_comp <B...>()>
{
static_assert(A(), "");
};
两者都包含断言(分别是运行时或编译时)以确保第一个参数为 true。
现在给出以下输入
int main()
{
any_run (true, false, false);
any_comp <_true, _false, _false>();
}
运行时断言永远不会失败,但编译时断言会失败。这意味着any_run(false, false)
然而,从未被调用过 any_comp <_false, _false>
尽管 bool 常量表达式确实被实例化
A() || any_comp <B...>()
可以评估为 true
如果A() == true
无需实例化any_comp <B...>
.
我的问题是这个实验及其结论是否有效,以及标准对此有何评价。
这很重要,因为如果结论是有效的,我必须更仔细地重新实现几个编译时函数(具有更多的特化)以使编译更快,尽管我通常更喜欢让事情尽可能简单。
最佳答案
短路仅适用于||
的运行时级别。在编译时,您还需要其他东西,例如:
#include <type_traits>
template <typename T, typename U>
struct integral_or : U { };
template <typename U>
struct integral_or <std::true_type, U> : std::true_type { };
template <typename... A>
struct any_comp : std::false_type { };
template <typename A, typename... B>
struct any_comp <A, B...> : integral_or <A, any_comp <B...>>
{
static_assert(A(), "");
};
int main()
{
any_comp <std::true_type, std::false_type, std::false_type>();
}
关于c++ - bool 常量表达式中的冗余实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18931962/