gpt4 book ai didi

c++ - 在编译时评估 'if' 子句

转载 作者:行者123 更新时间:2023-12-03 00:57:32 24 4
gpt4 key购买 nike

考虑以下代码片段:

#include <limits>
#include <stdexcept>

void g(unsigned) {
// ...
}

template<typename UIntT>
void f(UIntT n)
{
if constexpr (std::numeric_limits<UIntT>::max() > std::numeric_limits<unsigned>::max())
{
if (n > std::numeric_limits<unsigned>::max())
throw std::length_error("Too long.");
}

g(n);
}

我想知道“if constexpr”子句在这里是否真的有用。难道编译器不够聪明,无法找出“if”子句对于给定的 UIntT 是否为真吗?如果是这样,这是标准规定的吗?

最佳答案

Aren't compilers smart enough to find out whether the if clause can ever be true for a given UIntT?

大多数都是。

If so, is this mandated by the standard?

不,一些优化已经被命名(RVO:s 等),并且后来被纳入语言标准,但 DEADC0DE 优化并未标准化(据我所知)。

...但是constexpr

合格的编译器不可能会在生成的二进制文件中保留该 block (如果条件为false) - 但您决定优化代码。

关于c++ - 在编译时评估 'if' 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58138867/

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