c++ - 定义不同于 constexpr 静态成员的声明

标签 c++ c++11 language-lawyer

<分区>

考虑代码

#include <iostream>

struct Foo
{
    constexpr static int n = 42;
};

const int Foo::n; // note const, NOT constexpr

int main()
{
    std::cout << Foo::n;
}

静态成员的定义与类内声明不同,即使用const代替constexpr。上面的代码是否合法,如果是,为什么?它用 gcc 和 clang 编译。如果我们分别在定义和声明中交换 constconstexpr,它也会编译。我知道 constexpr 暗示了变量的 const,但反之则不然。

最佳答案

我的两分钱,同时查看一些文档,如 that one .

实际上,它可能是有效的。

事实上,constexprconst 之间的区别主要在于它们的用途,但前者暗示后者是副作用。

还有一个更微妙的区别:constexpr 是一个说明符,而const 是一个类型限定符 .

特别是:

const’s primary function is to express the idea that an object is not modified through an interface

另一边:

constexpr’s primary function is to extend the range of what can be computed at compile time, making such computation type safe and also usable in compile-time contexts

或者更简洁来自here :

constexpr - specifies that the value of a variable or function can appear in constant expressions

不管怎样,它发生了:

constexpr in front of a variable definition [...] implies const

因此,尽管应该使用 constexpr 而不是 const 的原因很明确,并且每个人都倾向于记住:

constexpr is not a general purpose replacement for const (or vice versa)

事实上,使用 constexpr 你实际上是在说这个成员是隐式的 const (而且你对如何定义该成员有一组更具体的约束).

无论如何,一旦定义,该成员只不过是具有 const 类型限定符(可用于常量表达式)的数据成员,这就是您在类中声明的内容。

关于c++ - 定义不同于 constexpr 静态成员的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34058118/

相关文章:

c++ - boost::program_options 的链接错误

c++ - 在构造函数中初始化静态函数指针

c++ - 覆盖 std::string 空终止符合法吗?

c++ - "aggregate or union type that includes one of the aforementioned types"严格别名规则发生了什么?

android - 无法构建 OpenCV Android 示例项目

c++ - 如何在 C++ 中使用 Boost::regex.hpp 库?

java - msgpack:C++ 和 java 之间的消息传递

java - 在 Java 中使用流进行序列化

c++ - 任意浮点值与无穷大相比如何?

c - `printf("%.-1s\n", "foo")` 会调用未定义的行为吗?