C++ 的 if constexpr

等级 5462 次按键

describe<T>() 结合 if constexpr 和类型特征在编译期选择描述。只有与 T 匹配的分支会被编译,因此每个实例只是返回一个字符串。

C++ 代码

// T 在调用时显式给出,例如 describe<int>()
1template<typename T>
2string describe() {
// 是否为整数类型(int、char、bool 等);在编译期判断
3 if constexpr (is_integral_v<T>) {
4 return "integer type";
// 浮点类型:float、double、long double
5 } else if constexpr (is_floating_point_v<T>) {
6 return "floating point type";
// 指针类型,例如 int*
7 } else if constexpr (is_pointer_v<T>) {
8 return "pointer type";
// 其他类型,例如 string
9 } else {
10 return "other type";
11 }
12}
13
// 输出“int: integer type”
14cout << "int: " << describe<int>() << endl;
// 输出“double: floating point type”
15cout << "double: " << describe<double>() << endl;
// 输出“int*: pointer type”
16cout << "int*: " << describe<int*>() << endl;
// string 不属于以上任何一种:输出“string: other type”
17cout << "string: " << describe<string>() << endl;

运行结果

int: integer type
double: floating point type
int*: pointer type
string: other type
用这段代码练习打字

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

这段代码中的符号

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

  • <× 32
  • "× 16
  • ;× 8
  • (× 8
  • )× 8
  • >× 8
  • _× 7
  • {× 5
  • }× 5
  • :× 4

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

← 返回 C++ 打字练习