问题描述
我想在类中定义一个常量,其值是最大可能的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:
t工作,但两件事看起来很奇怪我:
I understand why this doesn't work, but two things look weird to me:
-
在我看来,一个自然的决定使用的值常量表达式。为什么语言设计者决定让 max()一个函数,因此不允许这种用法?
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
这不意味着我应该能够在我的场景中使用它,
Doesn't it mean that I should be able to use it in my scenario and doesn't it contradict the error message?
谢谢。
推荐答案
虽然目前的标准缺乏支持,但对于整数类型为您提供了编译时常数 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:
请注意,它添加了:
像其他人已经提到的 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!