没有 Concepts 的 C++:
template <typename T>
T twice(T x) {
return x + x;
}
twice(42); // ✅ 正常
twice("hello"s); // ✅ 正常(string 可以 +)
twice(std::mutex{}); // ❌ 编译报错,5 万行报错信息!!
错误信息长啥样?
error: no match for 'operator+' (operand types are 'std::mutex' and 'std::mutex')
note: candidate: 'std::mutex::mutex(const std::mutex&)' <near match>
note: conversion of argument 1 would be ill-formed
... (50 行后续错误)
... (深入各种模板实例化失败上下文)
... (100 行库内部代码)
有了 Concepts 的 C++ 20:
template <typename T>
concept Addable = requires(T a, T b) { { a + b } -> std::convertible_to<T>; };
template <Addable T>
T twice(T x) {
return x + x;
}
twice(std::mutex{}); // ❌ 报错:'std::mutex' 不满足 'Addable' 约束
就一行。没有 5 万行堆栈。编译器直接告诉你"不满足约束"。
这就是 Concepts 的核心价值:让模板的错误信息从"编译器内部堆栈"变成"你写的约束条件"。