`constexpr` 指明这个要在编译期处理;`const` 则没有指明,可以在运行时处理。
by whhsteven @ 2022-09-29 16:17:25
@[whhsteven](/user/118109) 我知道,但是不加 `constexpr` 运行时算的速度比编译器算的速度差这么多???
by esquigybcu @ 2022-09-29 16:19:53
@[esquigybcu](/user/384214) 编译器计算能力是非常有限的。
当年C++11引入constexpr函数的时候,仅允许函数里包含一条语句(也就是一条return语句)。C++14草案提议放宽这一限制的时候,获得了一众的好评,唯独开发编译器的人当时觉得这简直是噩梦。
by GKxx @ 2022-09-29 16:26:32
@[esquigybcu](/user/384214) 想开点,虽然加了constexpr之后编译很慢,但是运行快啊
如果你真的对编译器如何处理constexpr函数感兴趣的话[看这里](https://stackoverflow.com/questions/65029891/how-are-constexpr-functions-implemented-by-compilers)
It's too much for a simple answer.
by GKxx @ 2022-09-29 16:30:55
@[GKxx](/user/72071) Woah, thanks!
by esquigybcu @ 2022-09-29 16:57:47
@[esquigybcu](/user/384214) 所以是不是所有 const 都可以写成 constexpr 捏
by 已注销HDyr!RS @ 2022-09-29 17:19:20
@[esquigybcu](/user/384214)
另外,事实上在有constexpr之前,人们就已经发现充分利用编译器计算能力的方法了,也就是所谓的“模板元编程”。例如下面是一个编译期计算阶乘的“函数”:
```cpp
template <unsigned N>
struct Factorial {
static const unsigned long long value = N * Factorial<N - 1>::value;
};
template <>
struct Factorial<0> {
static const unsigned long long value = 1;
};
int x = Factorial<10>::value;
```
在编译器生成的汇编代码里,你应该只会看到
```assembly
x:
.long 3628800
```
by GKxx @ 2022-09-29 17:21:46
@[Miniqwq](/user/528351) 不是。`const`的语义是“一经初始化便不可更改”,而`constexpr`的语义是“编译期可以计算”。`constexpr`的值一定是`const`,而反之不然。
by GKxx @ 2022-09-29 17:22:36
@[GKxx](/user/72071) 感谢 orz
by 已注销HDyr!RS @ 2022-09-29 18:16:31