命名空间
变体
操作

std::visit

来自 cppreference.cn
< cpp‎ | utility‎ | variant
 
 
 
 
定义于头文件 <variant>
template< class Visitor, class... Variants >
constexpr /* 见下方 */ visit( Visitor&& v, Variants&&... values );
(1) (C++17 起)
template< class R, class Visitor, class... Variants >
constexpr R visit( Visitor&& v, Variants&&... values );
(2) (C++20 起)
帮助模板
template< class... Ts >
auto&& as-variant( std::variant<Ts...>& value );
(3) (仅作说明*)
template< class... Ts >
auto&& as-variant( const std::variant<Ts...>& value );
(4) (仅作说明*)
template< class... Ts >
auto&& as-variant( std::variant<Ts...>&& value );
(5) (仅作说明*)
template< class... Ts >
auto&& as-variant( const std::variant<Ts...>&& value );
(6) (仅作说明*)

将访问器 v (一个可以用来自 Variants 的任意类型组合调用的可调用 (Callable) 对象)应用于 Variants values

给定 VariantBasesdecltype(as-variant(std::forward<Variants>(values))...(一个包含 sizeof...(Variants) 个类型的包)。

1) 调用 v,如同通过

INVOKE(std::forward<Visitor>(v),
       std::get<indices>(std::forward<VariantBases>(values))...)
,

其中 indicesas-variant(values).index()...
2) 调用 v,如同通过

INVOKE<R>(std::forward<Visitor>(v),
          std::get<indices>(std::forward<VariantBases>(values))...)
,

其中 indicesas-variant(values).index()...

这些重载仅当 VariantBases 中的每个类型都是有效类型时才参与重载决议。如果由 INVOKEINVOKE<R>(C++20 起) 表示的表达式是无效的,或者对于不同的 indicesINVOKEINVOKE<R>(C++20 起) 的结果具有不同的类型或值类别,则程序非良构。

3-6) 仅用于阐释的 as-variant 函数模板接受一个其类型可以被推导std::variant<Ts...> 的值(即,要么是 std::variant<Ts...>,要么是从 std::variant<Ts...> 派生的类型),并返回具有相同 const 限定和值类别的 std::variant 值。
3,4) 返回 value
5,6) 返回 std::move(value)

目录

[编辑] 参数

v - 一个可调用 (Callable) 对象,它接受来自 Variants 中每个 variant 的每一种可能的备选类型
values - 要传递给访问器的 variant 列表

[编辑] 返回值

1) INVOKE 操作的结果。返回类型是通过对结果应用 decltype 获得的类型。
2) 如果 R 是(可能 cv 限定的)void,则无返回值;否则为 INVOKE<R> 操作的结果。
3-6)value 转换而来的 std::variant 值。

[编辑] 异常

如果对于 values 中的任何 variant value_ias-variant(value_i).valueless_by_exception()true,则抛出 std::bad_variant_access

[编辑] 复杂度

当 variant 的数量为零或一时,可调用对象的调用以常数时间实现;也就是说,它不依赖于 variant 中可存储的类型数量。

如果 variant 的数量大于一,可调用对象的调用没有复杂度要求。

[编辑] 注意

n(1 * ... * std::variant_size_v<std::remove_reference_t<VariantBases>>),实现通常会为 std::visit 的每个特化生成一个等价于包含 n 个函数指针的(可能多维的)数组的表,这类似于虚函数的实现。

实现也可能为 std::visit 生成一个带有 n 个分支的 switch 语句(例如,当 n 不大于 256 时,MSVC STL 实现使用 switch 语句)。

在典型的实现中,调用 v 的时间复杂度可以被认为等同于访问一个(可能多维的)数组中的元素或执行一个 switch 语句的时间复杂度。

特性测试 标准 特性
__cpp_lib_variant 202102L (C++23)
(DR17)
支持派生自 std::variant 的类的 std::visit

[编辑] 示例

#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
 
// the variant to visit
using value_t = std::variant<int, long, double, std::string>;
 
// helper type for the visitor #4
template<class... Ts>
struct overloaded : Ts... { using Ts::operator()...; };
// explicit deduction guide (not needed as of C++20)
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
 
int main()
{
    std::vector<value_t> vec = {10, 15l, 1.5, "hello"};
 
    for (auto& v: vec)
    {
        // 1. void visitor, only called for side-effects (here, for I/O)
        std::visit([](auto&& arg){ std::cout << arg; }, v);
 
        // 2. value-returning visitor, demonstrates the idiom of returning another variant
        value_t w = std::visit([](auto&& arg) -> value_t { return arg + arg; }, v);
 
        // 3. type-matching visitor: a lambda that handles each type differently
        std::cout << ". After doubling, variant holds ";
        std::visit([](auto&& arg)
        {
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same_v<T, int>)
                std::cout << "int with value " << arg << '\n';
            else if constexpr (std::is_same_v<T, long>)
                std::cout << "long with value " << arg << '\n';
            else if constexpr (std::is_same_v<T, double>)
                std::cout << "double with value " << arg << '\n';
            else if constexpr (std::is_same_v<T, std::string>)
                std::cout << "std::string with value " << std::quoted(arg) << '\n';
            else
                static_assert(false, "non-exhaustive visitor!");
        }, w);
    }
 
    for (auto& v: vec)
    {
        // 4. another type-matching visitor: a class with 3 overloaded operator()'s
        // Note: The `(auto arg)` template operator() will bind to `int` and `long`
        //       in this case, but in its absence the `(double arg)` operator()
        //       *will also* bind to `int` and `long` because both are implicitly
        //       convertible to double. When using this form, care has to be taken
        //       that implicit conversions are handled correctly.
        std::visit(overloaded{
            [](auto arg) { std::cout << arg << ' '; },
            [](double arg) { std::cout << std::fixed << arg << ' '; },
            [](const std::string& arg) { std::cout << std::quoted(arg) << ' '; }
        }, v);
    }
}

输出

10. After doubling, variant holds int with value 20
15. After doubling, variant holds long with value 30
1.5. After doubling, variant holds double with value 3
hello. After doubling, variant holds std::string with value "hellohello"
10 15 1.500000 "hello"

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 2970 C++17 重载 (1) 的返回类型未保留 INVOKE 操作结果的值类别
value category of the result of the INVOKE operation
保留
LWG 3052
(P2162R2)
C++17 Variants 中任何类型不是 std::variant,则效果未指定
in Variants is not a std::variant
已指定

[编辑] 参见

(C++26)
使用 variant 持有的参数调用提供的函数对象
(公开成员函数) [编辑]
与另一个 variant 交换
(公开成员函数) [编辑]