std::variant::visit(3)
π 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β aCallablethat accepts every possible alternative from the variantselfβ variant to pass to the visitor
π Return value π
- 1) The result of the
std::visitinvocation. - 2) Nothing if
Ris (possibly cv-qualified)void; otherwise the result of thestd::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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms