C/C++:std::get

时间:2025-03-03 12:41:47

模板函数std::get()是一个辅助函数,它能够获取到容器的第n 个元素。模板参数的实参必须是一个在编译时可以确定的常量表达式,编译时会对它检查。

#include <variant>
#include <string>
 
int main()
{
    std::variant<int, float> v{12}, w;
    int i = std::get<int>(v);
    w = std::get<int>(v);
    w = std::get<0>(v); // 效果同前一行
 
//  std::get<double>(v); // 错误: [int, float] 中无 double
//  std::get<3>(v);      // 错误:合法的 index 值是 0 和 1
 
    try {
      std::get<float>(w); // w 含有 int ,非 float :将抛出异常
    }
    catch (std::bad_variant_access&) {}
}

#include <iostream>
#include <string>
#include <tuple>
 
int main()
{
    auto t = std::make_tuple(1, "Foo", 3.14);
 
    // Index-based access
    std::cout << "( " << std::get<0>(t)
              << ", " << std::get<1>(t)
              << ", " << std::get<2>(t)
              << " )\n";
 
    // Type-based access (C++14 or later)
    std::cout << "( " << std::get<int>(t)
              << ", " << std::get<const char*>(t)
              << ", " << std::get<double>(t)
              << " )\n";
 
    // Note: std::tie and structured binding may also be used to decompose a tuple.
}