gpt4 book ai didi

c++ - 逻辑短路是否不适用于 if-constexpr?

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:04 25 4
gpt4 key购买 nike

在正常的 if 条件下,短路有效。

然而,对于 if-constexpr 的尝试短路不起作用:

#include <iostream>
template <typename ... Args>
void foo(Args... args) {
std::string a;
// for the call of foo, sizeof...(args) = 0, so a > 2 shouldn't be evaluated.
if constexpr (sizeof...(args) == 0 || a > 2) {
std::cout << "ASD" << '\n';
}
}

int main() {
foo();
}

Demo

编辑:似乎很多评论都与我的尝试相去甚远。我只会引用@chris 的评论:

People seem to be missing the point, so here's a better example of why this is useful:

if constexpr (sizeof...(Ts) > 0 && is_integral_v<first_t<Ts...>>) { 
/* corresponding logic */
}

Currently, this requires nested constexpr ifs

目前看来这是不可能的,唯一的解决方法是编写嵌套的 ifs。

最佳答案

表达式 a > 2 需要在语法和语义上有效,否则,编译器不能排除它会返回某种 || 运算符的类型重载了。只有内置的 || 运算符具有短路行为。

但是,表达式 a > 2 不会被计算。您可以通过将 std::string a 更改为 int a(未初始化)来验证这一点:表达式 a > 2 的计算结果为 undefined行为,因此在常量表达式中不允许对 a > 2 求值。

关于c++ - 逻辑短路是否不适用于 if-constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46834258/

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