在常量表达式中使用numeric_limits :: max() [英] Using numeric_limits::max() in constant expressions

查看:312
本文介绍了在常量表达式中使用numeric_limits :: max()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在类中定义一个常量,其值是最大可能的int。类似的东西:

I would like to define inside a class a constant which value is the maximum possible int. Something like this:

class A
{
    ...
    static const int ERROR_VALUE = std::numeric_limits<int>::max();
    ...
}

此声明无法使用以下消息:

This declaration fails to compile with the following message:


numeric.cpp:8:error:'std :: numeric_limits :: max()'不能出现在常量表达式
numeric.cpp:8:错误:函数调用不能出现在常量表达式中

numeric.cpp:8: error: 'std::numeric_limits::max()' cannot appear in a constant-expression numeric.cpp:8: error: a function call cannot appear in a constant-expression

t工作,但两件事看起来很奇怪我:

I understand why this doesn't work, but two things look weird to me:


  1. 在我看来,一个自然的决定使用的值常量表达式。为什么语言设计者决定让 max()一个函数,因此不允许这种用法?

  1. It seems to me a natural decision to use the value in constant expressions. Why did the language designers decide to make max() a function thus not allowing this usage?

1


对于在numeric_limits模板中声明为static const的所有成员,specializations应以这样的方式定义这些值,常数表达式。

For all members declared static const in the numeric_limits template, specializations shall define these values in such a way that they are usable as integral constant expressions.

这不意味着我应该能够在我的场景中使用它,

Doesn't it mean that I should be able to use it in my scenario and doesn't it contradict the error message?

谢谢。

推荐答案

虽然目前的标准缺乏支持,但对于整数类型 Boost.IntegerTraits 为您提供了编译时常数 const_min const_max

While the current standard lacks support here, for integral types Boost.IntegerTraits gives you the compile time constants const_min and const_max.

问题出自§9.4.2/ 4



The problem arises from §9.4.2/4:


如果静态数据成员是const整数或const枚举类型,它在类定义中的声明可以指定一个常量初始化器,积分常数表达式(5.19)。

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions.

请注意,它添加了:


如果在程序中使用的成员仍然在命名空间范围内定义,并且命名空间范围定义不包含初始化器。

The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

像其他人已经提到的 numeric_limit s min() max()不是整型常数表达式,即编译时常数。

As others already mentioned numeric_limits min() and max() simply aren't integral constant expressions, i.e. compile time constants.

这篇关于在常量表达式中使用numeric_limits :: max()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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