【问题标题】:Redundant instantiations in boolean constant expressions布尔常量表达式中的冗余实例化
【发布时间】:2013-09-21 11:21:38
【问题描述】:

我有一个 n-any 布尔值 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 &lt;_false, _false&gt; 确实会被实例化,尽管布尔常量表达式

A() || any_comp <B...>()

如果A() == true 无需实例化any_comp &lt;B...&gt;,则可以评估为true

我的问题是这个实验及其结论是否有效,以及标准对此有何看法。

这很重要,因为如果结论是有效的,我必须更仔细地重新实现几个编译时函数(具有更多的专业化)以加快编译速度,尽管我通常更喜欢让事情尽可能简单。

【问题讨论】:

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


    【解决方案1】:

    短路仅适用于|| 的运行时级别。在编译时,您需要其他类似的东西:

    #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++03……我很高兴能扔掉所有像 integral_and 这样的函数出现复杂的表达式。谢谢!
    • 您还可以重载布尔运算符以实现表达式模板并提供更清晰的语法(例如decltype( a() || b() &amp;&amp; c() )。像this
    猜你喜欢
    • 1970-01-01
    • 2017-04-26
    • 2016-07-13
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多