首页 > 解决方案 > 如果有多个 if 语句,我们是否需要多个 if constexpr (...) ?

问题描述

我知道if constexpr(bool_test)编译器会丢弃else语句及其正文内容,反之亦然,具体取决于表达式的计算结果为真或假。

但是,如果我们有多个语句if else if,我们需要constexpr为每个if语句指定还是一个就足够了?

例如:

#include <type_traits>

class test { };

template <typename T>
struct is_test1 : public std::false_type { };

template <typename T>
struct is_test2 : public std::false_type { };

template <typename T>
struct is_test3 : public std::false_type { };

template<>
struct is_test3<test> : public std::true_type { };

int main()
{
    if constexpr(is_test1<test>::value)
    {

    }
    else if constexpr(is_test2<test>::value)
    {

    }
    else if constexpr(is_test3<test>::value)
    {

    }
    else
    {

    }
}

如果我们if constexpr只声明第一次会发生什么if,编译器如何处理其他if的它们是编译时表达式,即使没有constexpr指定,编译器也会丢弃其余的?

例如,我们可以改为这样写,但编译器是否会丢弃除计算结果为 true 的所有内容:

int main()
{
    if constexpr (is_test1<test>::value)
    {

    }
    else if (is_test2<test>::value)
    {

    }
    else if (is_test3<test>::value)
    {

    }
    else
    {

    }
}

标签: c++if-statementlanguage-lawyerc++17constexpr

解决方案


推荐阅读