名稱空間
變體
操作

std::visit

來自 cppreference.com
< 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 交換
(公開成員函式) [編輯]