c++ - 如果有多个 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
{
}
}
解决方案
推荐阅读
- php - 如何用php连接mysql数据库?
- c# - 在 WPF 中,如何在 LostFocus 上进行绑定但在 PropertyChanged 上进行验证?
- javascript - 为什么我的下拉菜单只显示了一半?
- android - 如何使用 Flutter 使 Android 中的状态栏变暗?
- c - 为什么从用户信息输入时我必须在使用 fgets 之前使用 getchar
- python - 将 Python 数组转换为列表中的字符串 [Pandas]
- django - 如何知道您是否将两个套接字连接到 django 通道中的同一组通道层
- javascript - 打字稿中的嵌套数组过滤器()函数-总是返回true?
- azure - Azure 媒体服务许可证密钥成本/计数
- r - 如何为已经用 R 编码的 BA、MA、PhD 的人添加分类变量、大学