Namespaces
Variants

std:: get (std::variant)

From cppreference.net
Utilities library
定义于头文件 <variant>
(1) (C++17 起)
template < std:: size_t I, class ... Types >

constexpr std:: variant_alternative_t < I, std:: variant < Types... >> &

get ( std:: variant < Types... > & v ) ;
template < std:: size_t I, class ... Types >

constexpr std:: variant_alternative_t < I, std:: variant < Types... >> &&

get ( std:: variant < Types... > && v ) ;
template < std:: size_t I, class ... Types >

constexpr const std:: variant_alternative_t < I, std:: variant < Types... >> &

get ( const std:: variant < Types... > & v ) ;
template < std:: size_t I, class ... Types >

constexpr const std:: variant_alternative_t < I, std:: variant < Types... >> &&

get ( const std:: variant < Types... > && v ) ;
(2) (C++17 起)
template < class T, class ... Types >
constexpr T & get ( std:: variant < Types... > & v ) ;
template < class T, class ... Types >
constexpr T && get ( std:: variant < Types... > && v ) ;
template < class T, class ... Types >
constexpr const T & get ( const std:: variant < Types... > & v ) ;
template < class T, class ... Types >
constexpr const T && get ( const std:: variant < Types... > && v ) ;
1) 基于索引的值访问器:若 v. index ( ) == I ,则返回存储在 v 中的值的引用。否则抛出 std::bad_variant_access 。当 I 不是 variant 中的有效索引时,该调用属于病式结构。
2) 基于类型的值访问器:若 v 持有备选类型 T ,则返回存储在 v 中的值的引用。否则抛出 std::bad_variant_access 。若 T 不是 Types... 中的唯一元素,则该调用格式错误。

目录

模板参数

I - 要查找的索引
T - 要查找的唯一类型
Types... - 构成 variant 的类型

参数

v - 一个 variant

返回值

引用存储在 variant 中的值。

异常

1,2) 出错时抛出 std::bad_variant_access

示例

#include <iostream>
#include <string>
#include <variant>
int main()
{
    std::variant<int, float> v{12}, w;
    std::cout << std::get<int>(v) << '\n';
    w = std::get<int>(v);
    w = std::get<0>(v); // 效果与上一行相同
//  std::get<double>(v); // 错误:[int, float] 中不存在 double 类型
//  std::get<3>(v);      // 错误:有效索引值为 0 和 1
    try
    {
        w = 42.0f;
        std::cout << std::get<float>(w) << '\n'; // 正常,输出 42
        w = 42;
        std::cout << std::get<float>(w) << '\n'; // 抛出异常
    }
    catch (std::bad_variant_access const& ex)
    {
        std::cout << ex.what() << ": w 包含的是 int 而非 float\n";
    }
}

可能的输出:

12
42
Unexpected index: w contained int, not float

参见

(C++17)
获取指向 variant 对象值的指针(通过索引或唯一类型),错误时返回空指针
(函数模板)
访问 tuple 的指定元素
(函数模板)
访问 array 的元素
(函数模板)
访问 pair 的元素
(函数模板)
std::ranges::subrange 获取迭代器或哨兵
(函数模板)
std::complex 获取实部或虚部的引用
(函数模板)