gpt4 book ai didi

c++ - bool 常量表达式中的冗余实例化

转载 作者:搜寻专家 更新时间:2023-10-31 01:47:39 24 4
gpt4 key购买 nike

我有一个 n-any 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(), "");
};

两者都包含断言(分别是运行时或编译时)以确保第一个参数为真。

现在给出以下输入

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com