我想在一个类中定义一个常量,它的值是最大可能的 int。像这样的:
class A
{
...
static const int ERROR_VALUE = std::numeric_limits<int>::max();
...
}
此声明无法编译并显示以下消息:
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
我明白为什么这不起作用,但有两件事在我看来很奇怪:
在我看来,在常量表达式中使用值是很自然的决定。为什么语言设计者决定将 max() 设为一个函数,从而不允许这种用法?
规范在 18.2.1 中声称
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.
这不是说我应该可以在我的场景中使用它并且不与错误消息相矛盾吗?
谢谢。
最佳答案
看起来有点瑕疵...
在 C++0x 中,numeric_limits
将用 constexpr
标记所有内容,这意味着您将能够使用 min()
和 max()
作为编译时常量。
关于c++ - 在常量表达式中使用 numeric_limits::max(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2738435/