编译期编程与模板元编程
用 constexpr、concepts 与 CRTP 把工作挪到编译期
#为什么要把计算挪到编译期
编译期编程的核心动机只有两个:更快(运行时不做重复计算)和更早报错(不满足约束的代码根本编译不过)。Java 的泛型是类型擦除,运行时拿不到 T 的任何信息;Python 是动态语言,装饰器能做一点事但谈不上类型约束;TypeScript 有强大的类型体操,但类型在编译后全部消失,不产生任何代码。C++ 独树一帜——模板实例化真的生成代码,constexpr 求值真的在编译器里跑了一遍。代价是编译时间变长、错误信息变长,所以本章最后会讨论取舍。
先明确一个概念:C++ 的模板是图灵完备的,constexpr 求值器本质上是一个内嵌的解释器。这两套机制(模板元编程 TMP 和 constexpr 计算)目标相同,但风格差异巨大:TMP 靠类型推导和递归实例化,写法晦涩;constexpr 用普通函数语法,可读性好得多。现代 C++ 的指导原则是——能用 constexpr 就别用 TMP。
#constexpr 函数与变量、consteval
constexpr 修饰函数表示「如果参数都是编译期常量,这个函数可以在编译期求值」。注意它不是「必须」在编译期求值:同一个 constexpr 函数用运行时参数调用时,就是普通函数。C++20 的 consteval 才是强制编译期求值,运行时调用直接编译失败。
#include <array>
#include <iostream>
// constexpr 函数:既能编译期算,也能运行时算
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
// constexpr 变量:强制编译期求值
constexpr int f10 = factorial(10); // 编译期得到 3628800
// C++14 起 constexpr 函数可以有多语句、循环、局部变量
constexpr int fib(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; ++i) {
int t = a + b;
a = b;
b = t;
}
return a;
}
// C++20 consteval:必须在编译期求值
consteval int square_strict(int x) { return x * x; }
// 编译期生成查找表:运行时零成本
constexpr std::array<int, 11> make_table() {
std::array<int, 11> t{};
for (int i = 0; i <= 10; ++i) t[i] = factorial(i);
return t;
}
constexpr auto table = make_table();
int main() {
constexpr int a = square_strict(7); // OK
int runtime = 5;
int b = factorial(runtime); // OK:constexpr 函数降级为运行时
// int c = square_strict(runtime); // 编译错误:consteval 不接受运行时值
std::cout << f10 << " " << fib(10) << " " << a << " " << b << "\n";
std::cout << "table[6] = " << table[6] << "\n";
// static_assert:编译期断言,失败则编译中断
static_assert(factorial(5) == 120, "math broken");
static_assert(table[10] == 3628800);
}static_assert 是编译期编程的单元测试。把「不变量」写进代码,比写注释可靠得多。
#模板递归与编译期计算(旧式 TMP)
在 constexpr 成熟之前,编译期计算靠模板递归:用特化作为递归终止条件,结果存在 static constexpr 成员或 ::value 里。下面这段是经典写法,你仍会在老代码和第三方库里遇到它:
#include <iostream>
#include <type_traits>
// 主模板:递归
template <int N>
struct Factorial {
static constexpr int value = N * Factorial<N - 1>::value;
};
// 特化:递归终止条件,必须有
template <>
struct Factorial<0> {
static constexpr int value = 1;
};
// 类型层面的递归:编译期判断类型列表中是否含 T
template <typename T, typename... Ts>
struct Contains;
template <typename T>
struct Contains<T> {
static constexpr bool value = false; // 空包,终止
};
template <typename T, typename Head, typename... Tail>
struct Contains<T, Head, Tail...> {
static constexpr bool value =
std::is_same_v<T, Head> || Contains<T, Tail...>::value;
};
int main() {
std::cout << Factorial<10>::value << "\n";
std::cout << std::boolalpha << Contains<int, char, double, int>::value << "\n";
// C++14 起可用变量模板简写
std::cout << Factorial<5>::value << "\n";
}这类代码的三个痛点:递归深度有编译器上限(常见 900 层);实例化链条长导致编译慢;出错时错误信息是几十层模板栈。现代写法应当用 if constexpr + 折叠表达式替代:
// 同样的功能,C++17 一行搞定
template <typename T, typename... Ts>
constexpr bool contains_v = (std::is_same_v<T, Ts> || ...);#SFINAE 与 std::enable_if
SFINAE(Substitution Failure Is Not An Error,替换失败不是错误)是 C++11/14 时代约束模板的唯一手段:当模板参数替换失败时,这个候选从重载集中静默移除,而不是报错。
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
// 方式一:返回值上做 SFINAE —— 只对整型启用
template <typename T>
std::enable_if_t<std::is_integral_v<T>, T> twice(T x) {
return x * 2;
}
// 方式二:模板参数默认值上做 SFINAE —— 只对浮点启用
template <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
T twice(T x) {
return x + x;
}
// 方式三:检测某个成员是否存在(经典的 void_t 技巧)
template <typename T, typename = void>
struct HasSize : std::false_type {};
template <typename T>
struct HasSize<T, std::void_t<decltype(std::declval<T>().size())>> : std::true_type {};
template <typename T>
constexpr bool has_size_v = HasSize<T>::value;
int main() {
std::cout << twice(21) << "\n"; // 42,走整型版本
std::cout << twice(2.5) << "\n"; // 5.0,走浮点版本
// twice(std::string("x")); // 编译错误:无匹配重载(报错信息极长)
std::cout << std::boolalpha
<< has_size_v<std::vector<int>> << " " // true
<< has_size_v<int> << "\n"; // false
}SFINAE 能工作,但错误信息动辄几百行,且逻辑藏在类型系统里难以阅读。这正是 C++20 Concepts 要解决的问题。
#type_traits:类型萃取
<type_traits> 是一张「类型的数据库」,分三类:判断型(is_integral_v 返回 bool)、变换型(remove_const_t、decay_t 返回新类型)、关系型(is_same_v、is_convertible_v)。C++14 之后每个 trait 都有 _v / _t 后缀的简写别名,写起来清爽很多。
常用的变换:std::decay_t<T> 模拟按值传参发生的退化(去引用、去 const、数组转指针、函数转函数指针),在泛型代码里保存参数时几乎是必须的;std::remove_reference_t<T> 配合完美转发。
#C++20 Concepts:约束模板的正确方式
Concept 把「这个模板要求 T 满足什么」写成一等公民,带来三个直接收益:错误信息可读、重载可以按约束精确分派、意图自文档化。
// C++20
#include <concepts>
#include <iostream>
#include <string>
#include <vector>
// 自定义 concept:要求类型可加且可流输出
template <typename T>
concept Addable = requires(T a, T b) {
{ a + b } -> std::convertible_to<T>;
};
template <typename T>
concept Printable = requires(T a, std::ostream& os) {
{ os << a } -> std::same_as<std::ostream&>;
};
// 用法一:concept 直接替代 typename
template <std::integral T>
T twice(T x) { return x * 2; }
// 用法二:requires 子句,支持组合约束
template <typename T>
requires Addable<T> && Printable<T>
T add_and_show(T a, T b) {
T r = a + b;
std::cout << r << "\n";
return r;
}
// 用法三:简写函数模板(abbreviated function template)
std::integral auto square(std::integral auto x) { return x * x; }
// 用法四:多个重载按约束强弱自动选择
template <std::integral T> void describe(T) { std::cout << "integral\n"; }
template <std::floating_point T> void describe(T) { std::cout << "floating\n"; }
int main() {
std::cout << twice(21) << "\n"; // 42
std::cout << square(9) << "\n"; // 81
add_and_show(2, 3);
add_and_show(std::string("a"), std::string("b"));
describe(1); // integral
describe(1.5); // floating
// twice(1.5); // 错误信息:double 不满足 std::integral(清晰!)
}标准库提供了一批现成的 concept:std::integral、std::floating_point、std::invocable、std::same_as、std::convertible_to、std::ranges::range 等。写泛型代码时优先复用它们,别自己造轮子。对比 Java 的泛型边界 <T extends Comparable<T>>:能力接近,但 C++ 的 requires 表达式可以检查任意表达式的合法性(比如「a + b 是否能编译」),这比 Java 只能约束继承关系强得多。
#CRTP:静态多态
CRTP(Curiously Recurring Template Pattern,奇异递归模板模式)手法是:基类是模板,派生类把自己作为模板参数传给基类。基类通过 static_cast 向下调用派生类实现,没有虚函数、没有虚表、没有间接调用,可以被完全内联。
#include <iostream>
#include <string>
// CRTP 基类:提供通用接口,转发到派生类实现
template <typename Derived>
class PrintableBase {
public:
void print() const {
static_cast<const Derived*>(this)->print_impl();
}
std::string to_string() const {
return static_cast<const Derived*>(this)->to_string_impl();
}
};
class Point : public PrintableBase<Point> {
public:
Point(double x, double y) : x_(x), y_(y) {}
void print_impl() const {
std::cout << "Point(" << x_ << ", " << y_ << ")\n";
}
std::string to_string_impl() const {
return "Point[" + std::to_string(x_) + "," + std::to_string(y_) + "]";
}
private:
double x_, y_;
friend class PrintableBase<Point>; // 或用 public 成员
};
// 另一个典型应用:编译期计数器 / 对象池
template <typename Derived>
struct Counter {
static inline int count = 0;
Counter() { ++count; }
~Counter() { --count; }
static int alive() { return count; }
};
struct Widget : Counter<Widget> {}; // 每个派生类有独立的静态计数
int main() {
Point p{1.0, 2.0};
p.print();
std::cout << p.to_string() << "\n";
Widget a, b;
{ Widget c; std::cout << "alive: " << Widget::alive() << "\n"; } // 3
std::cout << "alive: " << Widget::alive() << "\n"; // 2
}与第一篇讲的虚函数多态对比:动态多态支持运行时替换(容器里放不同派生类)、二进制体积大、每次调用一次间接跳转;CRTP 要求类型在编译期确定,但零开销。Qt 的很多工具类、Eigen 矩阵库、std::enable_shared_from_this 都用了 CRTP。 选择依据很简单:需要运行时决定类型就用虚函数,能编译期确定就用 CRTP。
#编译期与运行期的取舍
编译期计算不是免费的。三个真实代价:一是编译时间,重型模板元编程会让编译从秒级变分钟级;二是错误信息,即使有 concepts,深层实例化仍然难读;三是代码膨胀,模板为每种类型生成一份代码,二进制体积会涨。反过来,运行期计算的代价是每次执行都要算,且错误只能在运行时暴露(往往是崩溃)。
实用的判断标准:
- 常量表、单位换算、哈希字符串、类型 ID、长度固定的数学运算 → 编译期;
- 依赖用户输入、文件内容、网络数据的计算 → 运行期;
- 只是想提前发现错误 → 用
static_assert和 concept 约束,而不是把所有逻辑挪到编译期; - 团队项目里,优先写"能读懂"的版本,性能优化交给 profile 数据,而不是直觉。
#小结
constexpr函数可在编译期或运行期求值,consteval(C++20)强制编译期,constexpr变量一定在编译期求值;配static_assert做编译期断言。- 旧式 TMP 靠模板递归 + 特化终止,可读性差、编译慢、报错长;C++17 的
if constexpr与折叠表达式应作为首选替代。 - SFINAE 让替换失败的模板从重载集中静默移除,是 C++11/14 唯一的约束手段,但错误信息极难读。
- C++20 Concepts 用
requires表达式约束任意表达式合法性,错误信息清晰、支持按约束重载分派,新代码应全面采用。 - CRTP 用「派生类作为基类模板参数」实现静态多态,零虚表开销可内联;代价是类型必须编译期确定,无法运行时替换。
#练习
- 用
constexpr写一个编译期字符串长度与编译期 FNV-1a 哈希函数,并用static_assert验证"hello"的哈希值;说明为什么std::string不能用于 constexpr。 - 把上一章的
print_all改用if constexpr增强:对std::string加引号、对浮点保留两位小数、其余直接输出,要求不产生任何运行时分支。 - 定义 concept
Hashable,要求std::hash<T>{}(t)可编译且返回可转为size_t的类型;写一个只接受Hashable的make_key函数,分别传入int、std::string和一个自定义结构体验证。 - (进阶)用 CRTP 实现一个
Addable<T>基类,为所有派生类自动提供operator+,派生类只需实现add_impl;验证调用可被编译器完全内联(用-O2 -S观察汇编中无call指令)。