// 写法 1:template 前缀约束(最推荐,一眼看出模板类型受约束)
template <std::integral T>
T half(T x) { return x / 2; }
// 写法 2:auto 参数约束(简洁,类似泛型 lambda)
std::integral auto half(std::integral auto x) { return x / 2; }
// 写法 3:requires 子句(最灵活,可以写复杂条件)
template <typename T>
requires std::integral<T>
T half(T x) { return x / 2; }
选哪个?
- 场景 1:约束很简单(比如
std::integral、std::floating_point)→ 写法 1 或 2 都行。 - 场景 2:约束复杂(多个条件组合)→ 定义新 Concept + 写法 1。
- 场景 3:约束依赖多个模板参数 →
requires子句最自然。