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

标签 c++ c++11 instantiation template-meta-programming constant-expression

我有一个任意 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/

相关文章:

c++ - 这个数组拷贝是如何工作的?

C++ 警告:将 _U1 推导为 std::initializer_list<int>

c++ - 使用 MSVC 2013 初始化 `static constexpr double`

java - Mongodb中对象结构发生变化时无法实例化对象

c++ - 将数组作为参数传递时,调节内存的最有效方法是什么?

c++ - 按非惰性 lambda 表达式/投影排序

c++ - 模板和 is_same() 不起作用?

c++ - float /始终在对话框上方

c++ - 我可以在不重复签名的情况下实例化模板吗?

c++ - gurobi - 错误代码 = 10004 无法检索属性 'X'