跳转至

💡 一分钟速览:C++ const 全家桶一次讲透:const、constexpr、constinit、consteval 与类中 const 成员的边界,以及 C++23 deducing this 如何把四个 const/引用重载合成一个函数。

最后更新:2026-10-13

C++ const 全家桶

大纲

  • const
  • constexpr
  • C++20
  • consteval
  • constinit

注:本文所有代码示例已放星球。

1.const

const 是我们在学习 C++/C 时最早接触的关键字之一,通常作为 cv-qualifier 使用,表示对象不可变。它并不保证 编译时评估,具体何时评估由编译器决定。例如:

const int a = 1; // 编译时
const auto x = getdata(); // 运行时

const有时可以用于编译时常量表达式,但是有一些例外,例如:

const double count_1 = 3.3;
std::array<double, static_cast<int>(count_1)> moreDoubles1 {1.1, 2.2, 3.3};

此时便会报错:the value of 'count_1' is not usable in a constant expression

但是这样是正常的:

const int count = 3;
std::array<double, count> doubles {1.1, 2.2, 3.3};

本质在于编译时表达式求值,于是C++11引入了constexpr。

2.constexpr

constexpr 可以用来指定变量的值可以出现在常量表达式,此时只需要将前面例子的const变为constexpr,便可以正常运行。

constexpr double count_2 = 3.3;
std::array<double, static_cast<int>(count_2)> moreDoubles2 {1.1, 2.2, 3.3}; 

constexpr 并不一定只能在编译时执行。它的本质含义是 可以 在编译时计算,但如果在运行时使用 constexpr 变量或函数,它也可以在运行时执行。

例如:result1与result2完全不一样,result1是编译时计算,但是result2是运行时计算的,抛个疑问:你知道为什么吗?

所以并不是指定了constexpr的函数它就一定是编译时计算的。

constexpr int compileTimeSum(int a, int b) {
    return a + b;
}

int main() {
    constexpr int result1 = compileTimeSum(3, 5); 
    int x = 10;
    int result2 = compileTimeSum(x, 20);  
    return 0;
}

那么谁能保证呢?于是C++20来了。

3.C++20

3.1 consteval

consteval解决了上面的问题,它只能用于函数,并强制所有调用在编译时进行。如果我们此时将上面的constexpr改为consteval,此时result2会发生什么呢?

那便是报错:call to consteval function 'compileTimeSum(x, 20)' is not a constant expression

consteval int compileTimeSum(int a, int b) {
    return a + b;
}

int main() {
    constexpr int result1 = compileTimeSum(3, 5); 
    int x = 10;
    int result2 = compileTimeSum(x, 20);  
    return 0;
}

如果使用了consteval使用在变量上,也会报错:error: a variable cannot be declared 'consteval'。

https://en.cppreference.com/w/cpp/language/consteval

3.2 constinit

constinit可以强制静态或线程局部变量进行常量初始化。

  • 不能与 constexpr、consteval 一起使用
  • 一个非类型说明符,作用是assert
  • 保证变量是静态初始化
  • 只能用于 static 或者 thread_local

例如:下面会编译报错:error: 'constinit' can only be applied to a variable with static or thread storage duration

constinit int a = 100;  
int main() {  
      ++a; 
      constinit auto b = 100;  // error
      // b has thread storage duration
      constinit thread_local auto b = 100;
}

C++23 deducing this:const/引用重载一次写完

const 全家桶学到后面,几乎每个人都会撞上同一堵墙:一个 getter 想在 const 对象、非 const 对象、左值、右值上都表现正确,就得写四个长得几乎一样的重载——而且哪天有人只改了其中一个,四个就开始悄悄不一致。

C++23 的 deducing this(显式对象形参,提案 P0847)把这种复制粘贴干掉了。成员函数把自己的对象声明成显式参数,编译器推导它的类型时连同 const 属性和值类别一起推了,于是四个场景一个模板全包:

class Widget {
    int value_{42};

public:
    // Before C++23 you needed up to four overloads:
    //   int&  get() &       { return value_; }
    //   int   get() const&  { return value_; }
    //   int&& get() &&      { return std::move(value_); }
    //   ...
    // C++23 deducing this — one template covers them all:
    template <typename Self>
    auto&& get(this Self&& self) {
        return std::forward<Self>(self).value_;
    }
};

在 const 左值上调用 get() 时,Self 推导为 const Widget&;在右值上推导为 Widget&&,std::forward 顺势完成移动。前面讲的 const 判断功夫依然决定"什么该是 const"——deducing this 只是替你消掉重复劳动。

这个特性还顺手接下了 CRTP 的两个老活——混入行为、推导派生类型——而且不用基类模板那套样板代码。编译器支持:GCC 14+、Clang 18+、MSVC 自 VS 2022 17.2 起。

常见问题

deducing this 能替代 const 重载吗?

多数场景可以。一个作用在 Self&& 上的模板配合 std::forward,在 &、const&、&&、const&& 四种场景下都行为正确。只有当不同限定符下行为真的不同时才需要分开写重载——这种情况很少。

哪些编译器支持 deducing this?

GCC 14 及以上、Clang 18 及以上、MSVC 自 Visual Studio 2022 17.2 起。这是 C++23 特性,编译时加 -std=c++23(旧驱动用 c++2b)。

deducing this 和 CRTP 是一回事吗?

有重叠:两者都能推导最派生类型。deducing this 不需要基类模板、还能用在 lambda 上(递归 lambda!)、类层次保持干净;当混入必须做成可复用的基类时,CRTP 仍有用武之地。

相关主题

评论