std::get_if (std::variant)
来自 zh.cppreference.net
| 定义于头文件 <variant>
|
||
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;
|
(1) | (C++17 起) |
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;
|
(3) | (C++17 起) |
template< class T, class... Types >
constexpr std::add_pointer_t<const T>
get_if( const std::variant<Types...>* pv ) noexcept;
|
(4) | (C++17 起) |
1,2) 基于索引的不抛异常的访问器:如果
pv 不是空指针且 pv->index() == I,则返回指向 pv 所指 variant 中存储的值的指针。否则,返回空指针值。若 I 不是 variant 中的有效索引,则调用为非良构。3,4) 基于类型的不抛异常的访问器:等价于 (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!
参阅
|
(C++17)
|
根据索引或类型(若类型唯一)读取 variant 的值,错误时抛出异常
(函数模板) |