C++ 的 any类型

等级 5527 次按键

std::any 可以保存任意类型的单个值。循环中用 type() == typeid(...) 检查所存的类型,并用 any_cast 读取值。type().name() 输出的名称取决于编译器(示例输出来自 clang/libc++)。

C++ 代码

// 每个元素都可以保存不同类型的值
1vector<any> items;
// 依次存入 int、double、string 和 vector<int>
2items.push_back(42);
3items.push_back(3.14);
4items.push_back(string("hello"));
5items.push_back(vector<int>{1, 2, 3});
6
7for (const auto& item : items) {
// type().name() 由实现定义:这里为“i”和“d”,类则是修饰后的名称
8 cout << "Type: " << item.type().name() << " -> ";
// 把所存类型与 typeid 比较
9 if (item.type() == typeid(int))
// any_cast 读取值;类型不符时抛出 bad_any_cast
10 cout << any_cast<int>(item);
11 else if (item.type() == typeid(double))
12 cout << any_cast<double>(item);
13 else if (item.type() == typeid(string))
14 cout << any_cast<string>(item);
// vector<int> 不符合任何一个判断
15 else
16 cout << "[complex type]";
17 cout << endl;
18}
19
// 保存了 42,has_value() 为 true:输出“Has value: 1”
20cout << "Has value: " << items[0].has_value() << endl;

运行结果

Type: i -> 42
Type: d -> 3.14
Type: NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE -> hello
Type: NSt3__16vectorIiNS_9allocatorIiEEEE -> [complex type]
Has value: 1
用这段代码练习打字

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

这段代码中的符号

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

  • <× 27
  • (× 21
  • )× 21
  • ;× 12
  • .× 11
  • "× 10
  • _× 8
  • =× 6
  • >× 6
  • :× 3

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

← 返回 C++ 打字练习