请用 C++20 概念约束门类型参数
解读
国内大厂(阿里、腾讯、字节、华为)近两年的 C++ 岗面试里,**“模板元编程”与“C++20 Concepts”**是区分 P6/P7 与应届生的核心考点。
题目表面让“约束门类型参数”,实质考察三点:
- 能否用 concept 精确表达“门”的语法与语义要求;
- 能否把概念与 std::invocable、std::predicate 等标准概念组合,体现“零开销抽象”;
- 能否在报错信息里体现中文可读的自定义提示,这是工程落地时 Leader 重点关注的可维护性。
如果仅写 template<typename Gate> 而不加约束,会被直接追问“Concepts 优势在哪”,答不出即视为模板元编程基础薄弱。
知识点
- C++20 Concepts 语法:
concept关键字、requires 子句、合取/析取。 - 类型特征:
std::invocable、std::predicate、std::same_as。 - SFINAE 与 Concepts 对比:后者报错更短、可带自定义 static_assert 信息。
- 门(Gate)语义:可调用、返回 bool、最好支持反向(negate)与组合(and/or)。
- 国内编码规范:华为/阿里要求概念名首字母大写+CamelCase,与 STL 小写概念区分。
答案
#include <concepts>
#include <functional>
// 1. 定义门概念:可调用、参数为 Args...、返回 bool
template<typename G, typename... Args>
concept Gate = std::regular_invocable<G, Args...> &&
std::same_as<std::invoke_result_t<G, Args...>, bool>;
// 2. 使用概念约束模板参数
template<Gate<int> G>
bool check_int(G&& gate, int value) {
return std::forward<G>(gate)(value);
}
// 3. 支持组合:与门
template<Gate<int> G1, Gate<int> G2>
struct AndGate {
G1 g1;
G2 g2;
bool operator()(int x) const {
return g1(x) && g2(x);
}
};
// 4. 让 AndGate 本身也满足 Gate 概念
template<Gate<int> G1, Gate<int> G2>
AndGate(G1, G2) -> AndGate<G1, G2>;
static_assert(Gate<AndGate<std::greater<int>, std::less<int>>, int>);
// 5. 自定义报错信息(国内面试官常问)
template<typename G>
concept GateWithMsg = requires(G g) {
{ g() } -> std::same_as<bool>;
} || ([]<bool flag = false>() {
static_assert(flag, "**门类型必须可调用且返回 bool**");
return false;
}());
拓展思考
- 性能:Concepts 不会引入运行时开销,但约束表达式过于复杂会导致编译时间暴涨;国内交易公司(如量化私募)要求单文件增量编译 <2 s,需把概念拆到头文件并复用。
- 多语言接口:如果门类型由 Python 端注入(pybind11),需额外概念检测 is_nothrow_invocable,防止异常跨语言传播导致主链回滚。
- 概念版本化:阿里内部对 Concepts 采用inline namespace v1/v2方式做 ABI 兼容,面试可提“概念也能版本管理”,体现大型工程视角。
- 与 coroutine 结合:异步网关场景下,可写
AsyncGate概念约束 awaitable<bool>,展示对 C++20 协程的掌握,直接对标 P8 晋升答辩。