Namespaces
Variants

std:: get_if (std::variant)

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

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

get_if ( std:: variant < Types... > * pv ) noexcept ;
template < std:: size_t I, class ... Types >

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

get_if ( const std:: variant < Types... > * pv ) noexcept ;
(2) (C++17 起)
template < class T, class ... Types >

constexpr std:: add_pointer_t < T >

get_if ( std:: variant < Types... > * pv ) noexcept ;
template < class T, class ... Types >

constexpr std:: add_pointer_t < const T >

get_if ( const std:: variant < Types... > * pv ) noexcept ;
1) 基于索引的非抛出访问器:若 pv 不是空指针且 pv - > index ( ) == I ,则返回指向变体所存值的指针。否则返回空指针值。若 I 不是变体中的有效索引,则调用格式错误。
2) 基于类型的非抛出访问器:等同于 (1) ,其中 I 表示 T Types... 中从零开始的索引。如果 T 不是 Types... 中的唯一元素,则调用格式错误。

目录

模板参数

I - 要查找的索引
Type - 要查找的唯一类型

参数

pv - 指向变体的指针

返回值

指向所指向变体中存储的值的指针,若出错则为空指针。

示例

#include <iostream>
#include <variant>
int main()
{
    auto check_value = [](const std::variant<int, float>& v)
    {
        if (const int* pval = std::get_if<int>(&v))
            std::cout << "variant value: " << *pval << '\n';
        else
            std::cout << "failed to get value!" << '\n';
    };
    std::variant<int, float> v{12}, w{3.f};
    check_value(v);
    check_value(w);
}

输出:

variant value: 12
failed to get value!

参阅

根据索引或类型(若类型唯一)读取 variant 的值,错误时抛出异常
(函数模板)