Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::variant<Types...>::visit

      From cppreference.com
      <cpp‎ |utility‎ |variant
       
       
      Utilities library
       
       
      template<class Self,class Visitor>
      constexpr decltype(auto) visit( this Self&& self, Visitor&& vis);
      (1)(since C++26)
      template<class R,class Self,class Visitor>
      constexpr R visit( this Self&& self, Visitor&& vis);
      (2)(since C++26)

      Applies the visitorvis (aCallable that can be called with any combination of types from the variant) to the variant held byself.

      Given typeV asdecltype(std::forward_like<Self>(std::declval<variant>())), the equivalent call is:

      1)return std::visit(std::forward<Visitor>(vis),(V) self);.
      2)return std::visit<R>(std::forward<Visitor>(vis),(V) self);.

      Contents

      [edit]Parameters

      vis - aCallable that accepts every possible alternative from the variant
      self - variant to pass to the visitor

      [edit]Return value

      1) The result of thestd::visit invocation.
      2) Nothing ifR is (possibly cv-qualified)void; otherwise the result of thestd::visit<R> invocation.

      [edit]Exceptions

      Only throws if the call tostd::visit throws.

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_variant202306L(C++26)membervisit

      [edit]Example

      Run this code
      #include <print>#include <string>#include <string_view>#include <variant> struct Base{};struct Derived: Base{}; // helper type for the visitortemplate<class...Ts>struct overloads: Ts...{using Ts::operator()...;}; // the variant to visitusing var_t=std::variant<int,std::string, Derived>; int main(){constauto visitor= overloads{[](int i){std::print("int = {}\n", i);},[](std::string_view s){std::println("string = “{}”", s);},[](const Base&){std::println("base");}}; const var_t var1=42, var2="abc", var3= Derived(); #if (__cpp_lib_variant >= 202306L)    var1.visit(visitor);    var2.visit(visitor);    var3.visit(visitor);#else    std::visit(visitor, var1);    std::visit(visitor, var2);    std::visit(visitor, var3);#endif}

      Output:

      int = 42string = “abc”base

      [edit]See also

      (C++17)
      calls the provided functor with the arguments held by one or morevariants
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/variant/visit&oldid=179239"

      [8]ページ先頭

      ©2009-2025 Movatter.jp