c++ - 在常量表达式中使用 numeric_limits::max()

标签 c++ std constexpr numeric-limits

我想在一个类中定义一个常量,它的值是最大可能的 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

我明白为什么这不起作用,但有两件事在我看来很奇怪:

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

  2. 规范在 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/

相关文章:

c++ - 替换常量 : when to use static constexpr and inline constexpr?

c++ - 仅在 constexpr 函数体内的未计算上下文中使用的参数

c++ - C++ 17:在.cpp文件中定义静态constexpr成员函数

c++ - 有没有更有效的方法来检查列表中的两个数字是否相加为 int, k?

c++ - 具有特定颜色的像素不在它在 SFML 中的位置

c++ - erase-remove 习语 : did I just delete something?

c++ - CLR 干扰 C++ STD?

c++ - 指针算法的类型

c++ - 检查 std::thread 是否仍在运行

c++ - "p"数组如何使用 C++ std::normal_distribution 在以下代码中存储值?