为什么不ABS constexpr? [英] Why isn't abs constexpr?

查看:62
本文介绍了为什么不ABS constexpr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< cinttypes> 中,自C ++ 11起,存在以下两个重载:

In <cinttypes>, since C++11, there are the following two overloads:

std::intmax_t abs( std::intmax_t n );
std::intmax_t imaxabs( std::intmax_t n );

为什么这两个函数不是 constexpr

Why aren't those two functions constexpr?

推荐答案

我无法给出为什么 abs 的充分理由不能是 constexpr ,显然也不能是 gcc 。当我在此程序中使用 gcc 4.9.2 时:

I can't give a good reason for why abs couldn't be constexpr and apparently neither can gcc. When I use gcc 4.9.2 with this program:

#include <cstdlib>
#include <cinttypes>
#include <cassert>

constexpr intmax_t abs3 = std::abs(3);
constexpr intmax_t absneg3 = std::abs(-3);
int main()
{
    assert(abs3 == absneg3);
}

它可以编译并完成,没有任何警告或错误。您可以在此处尝试。但是, clang ++ (版本3.5.0)会引发编译时错误:

it compiles and runs to completion with no warnings or errors. You can try it here. However, clang++ (version 3.5.0) throws a compile-time error:


abs.cpp:6:20:错误:constexpr变量'abs3'必须通过常量表达式初始化。

abs.cpp:6:20: error: constexpr variable 'abs3' must be initialized by a constant expression.

我认为 clang ++ 实际上就在这里,因为在2011年标准的27.9.2节[c.files]中说:

I think that clang++ actually gets it right here, because in section 27.9.2 [c.files] of the 2011 standard, it says:


标头的内容与标准C库标头相同,但进行了以下更改:

The contents of header are the same as the Standard C Library header , with the following changes:

-标头包括标头代替

—并且仅当类型intmax_t指定扩展整数类型(3.9.1)时,才添加以下函数
签名:

— if and only if the type intmax_t designates an extended integer type (3.9.1), the following function signatures are added:

intmax_t abs(intmax_t);

intmax_t abs(intmax_t);

imaxdiv_t div(intmax_t,intmax_t);

imaxdiv_t div(intmax_t, intmax_t);

的语义应与函数签名intmax_t imaxabs(intmax_t)和
imaxdiv_t imaxdiv(intmax_t,intmax_

which shall have the same semantics as the function signatures intmax_t imaxabs(intmax_t) and imaxdiv_t imaxdiv(intmax_t, intmax_t), respectively.

C ++标准的当前工作草案(与2014年发布的版本相同),在17.6.5.6节中说明[constexpr.functions] :

In the current working draft of the C++ standard, as in the published 2014 version, it says in section 17.6.5.6 [constexpr.functions]:


该标准明确要求某些标准库函数为constexpr(7.1.5)。除了显式需要
的实现之外,实现不得将任何标准库函数签名声明为constexpr。

This standard explicitly requires that certain standard library functions are constexpr (7.1.5). An implementation shall not declare any standard library function signature as constexpr except for those where it is explicitly required.

结果,根据标准(您知道的),这些函数目前仍不是 constexpr ,但它们可以,如所示gcc 编译器。

So the result, for now, is that these functions are still not constexpr according to the standard (which you knew) but they could be, as demonstrated by the gcc compiler.

这篇关于为什么不ABS constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆