the*_*ang 3 c++ if-statement constexpr c++17
正常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();
}
Run Code Online (Sandbox Code Playgroud)
编辑:似乎很多评论都与我的尝试有所不同。我将引用@chris 的评论:
人们似乎没有抓住重点,所以这里有一个更好的例子来说明为什么这很有用:
Run Code Online (Sandbox Code Playgroud)if constexpr (sizeof...(Ts) > 0 && is_integral_v<first_t<Ts...>>) { /* corresponding logic */ }目前,这需要嵌套的 constexpr ifs
这似乎目前是不可能的,唯一的解决方法是编写嵌套的 ifs。
小智 5
表达式a > 2需要在句法和语义上有效,否则编译器不能排除它会返回||运算符重载的某种类型。只有内置||运算符具有短路行为。
但是,a > 2不会计算表达式。您可以通过更改std::string a为int a(left uninitialised):来验证这一点:表达式的求值a > 2将具有未定义的行为,因此a > 2常量表达式中不允许求值。
虽然可能不会评估条件,但您的程序不会编译,因为它无效 \xe2\x80\x93 您无法比较 astring和 an int。如果将随机字符放入 的第二个操作数中,您会得到类似的结果||。
| 归档时间: |
|
| 查看次数: |
462 次 |
| 最近记录: |