定义与constexpr静态成员的声明不同

vso*_*tco 6 c++ language-lawyer c++11

考虑一下代码

#include <iostream>

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

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

int main()
{
    std::cout << Foo::n;
}
Run Code Online (Sandbox Code Playgroud)

静态成员的定义与类内声明不同,即const使用而不是constexpr.代码是否合法,如果是,为什么?它用gcc和clang编译.如果我们互换const并分别constexpr在定义和声明中,它也会编译.我知道这constexpr意味着const变量,但不是相反.

sky*_*ack 1

My two cents, while looking at some documentation like that one.

\n\n

Actually, it could be valid.

\n\n

In fact, the difference between constexpr and const mainly relies into their purposes, but the former implies the latter as a side effect.

\n\n

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

\n\n

尤其:

\n\n
\n

const\xe2\x80\x99s 主要功能是表达对象不通过接口修改的想法

\n
\n\n

另一方面:

\n\n
\n

constexpr\xe2\x80\x99s 的主要功能是扩展编译时可计算的范围,使此类计算类型安全并可在编译时上下文中使用

\n
\n\n

或者从这里开始更简洁:

\n\n
\n

constexpr - 指定变量或函数的值可以出现在\xc2\xa0常量表达式中

\n
\n\n

不管怎样,会发生这样的情况:

\n\n
\n

变量定义前面的 constexpr\xc2\xa0 [...] 意味着 \xc2\xa0const

\n
\n\n

因此,即使应该使用constexpr而不是const is clear, and everybody tends to remember that:

\n\n
\n

constexpr\xc2\xa0 不是 \xc2\xa0const\xc2\xa0 的通用替代品(反之亦然)

\n
\n\n

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

\n\n

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

\n