C++ 的 概念

等级 5461 次按键

C++20 概念为模板参数的要求命名:Numeric 接受整数和浮点类型,Printable 接受任何可以写入 cout 的类型。不满足要求的调用会以清晰的错误编译失败。

C++ 代码

1template<typename T>
// Numeric:整数或浮点类型满足此概念
2concept Numeric = is_integral_v<T> || is_floating_point_v<T>;
3
4template<typename T>
// requires 列出对 T 必须合法的表达式
5concept Printable = requires(T t) {
// cout << t 必须能编译并返回 ostream&
6 { cout << t } -> same_as<ostream&>;
7};
8
// 用概念代替 typename,把 T 限制为数值类型
9template<Numeric T>
// 返回 x 的平方,类型与 x 相同
10T square(T x) { return x * x; }
11
// 只接受满足 Printable 的类型
12template<Printable T>
13void display(const T& value) {
14 cout << "Value: " << value << endl;
15}
16
// int:输出“Square of 5: 25”
17cout << "Square of 5: " << square(5) << endl;
// double:输出“Square of 2.5: 6.25”(square("a") 无法编译)
18cout << "Square of 2.5: " << square(2.5) << endl;
// 字符串字面量可输出:输出“Value: Hello Concepts”
19display("Hello Concepts");
// 输出“Value: 42”
20display(42);

运行结果

Square of 5: 25
Square of 2.5: 6.25
Value: Hello Concepts
Value: 42
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • <× 27
  • ;× 9
  • "× 8
  • >× 8
  • (× 7
  • )× 7
  • _× 6
  • {× 4
  • }× 4
  • :× 3

C++ 等级 5 的更多代码示例

← 返回 C++ 打字练习