std::variant::visit(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::variant::visit(3) πŸ’–

okay so bestie, this is the std::variant::visit(3) page from the C++ Standard Libary manual β€” yes, that's the manual name, typo and all, iconic. It's the member visit version and it's serving pure C++26 energy. Let's get into it. ✨

🫢 NAME 🫢

std::variant::visit β€” std::variant::visit (that's it, that's the name, periodt πŸ’…)

πŸ¦‹ Synopsis πŸ¦‹

          template< class Self, class Visitor >
       (1) (since C++26)
          constexpr decltype(auto) visit( this Self&& self, Visitor&& vis );
          template< class R, class Self, class Visitor >
       (2) (since C++26)
          constexpr R visit( this Self&& self, Visitor&& vis );

okay so this one is lowkey doing the absolute most, but here's the vibe: it applies the visitor vis (a Callable that can be called with any combination of types from the variant) to the variant held by self.

Given type V as decltype(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);.

🌸 Parameters 🌸

  • vis β€” a Callable that accepts every possible alternative from the variant
  • self β€” variant to pass to the visitor

πŸ’œ Return value πŸ’œ

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

πŸ”₯ Exceptions πŸ”₯

Only throws if the call to std::visit throws. no cap, that's the whole exception tea.

πŸŽ€ Notes πŸŽ€

the feature-test macro tea is:

  • Feature-test macro β€” Value β€” Std β€” Feature
  • __cpp_lib_variant β€” 202306L β€” (C++26) β€” member visit

🌈 Example 🌈

// Run this code β€” actually run it, bestie:

        #include <iostream>
        #include <string>
        #include <variant>

        // helper type for the visitor
        template<class... Ts>
        struct overloads : Ts... { using Ts::operator()...; };

        int main()
        {
            std::variant<int, std::string> var1{42}, var2{"abc"};

            auto use_int = [](int i){ std::cout << "int = " << i << '\n'; };
            auto use_str = [](std::string s){ std::cout << "string = " << s <<
       '\n'; };

        #if (__cpp_lib_variant >= 202306L)
            var1.visit(overloads{use_int, use_str});
            var2.visit(overloads{use_int, use_str});
        #else
            std::visit(overloads{use_int, use_str}, var1);
            std::visit(overloads{use_int, use_str}, var2);
        #endif
        }

πŸ“ Output πŸ“

        int = 42
        string = abc

mwah πŸ’‹ β€” source: http://cppreference.com, version/date: 2024.06.10, and this iconic page is std::variant::visit(3). bye bestie 🫢

πŸ“¦ where this page comes from