CKTIS / C++
std::visit — invoke a callable for active alternatives
std::visit, declared in <variant>, invokes a callable with the active value from each supplied std::variant object. With no variants, std::visit(visitor) invokes visitor with no arguments if that invocation is valid. Alternatives are selected at runtime, but the invocation is checked at compile time for every combination of alternatives.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <variant>
std::visit(visitor, variants...)
std::visit<R>(visitor, variants...)std::visit(visitor, variants...) from <variant> passes the active values to visitor. With several variants, it passes one value from each. It preserves the arguments' const qualification and value category.
The invocation must be valid for every combination of alternatives, not just the currently active combination. Without explicit R, all results must have the identical type and value category. The form std::visit<R>(visitor, variants...) specifies the result type; every invocation must satisfy conversion requirements for R, while R = void discards the result.
If any variant is valueless_by_exception(), the function throws std::bad_variant_access. The example uses Describe overloads returning std::string. The expected output is int: 42 followed by text: hello, each on its own line.
This entry covers the free function in C++23. The supplied address points to an evolving standard draft, not a frozen C++23 document. Setting a compiler flag does not attest operation in a production runtime.
Examples
#include <iostream>
#include <string>
#include <variant>
struct Describe {
std::string operator()(int value) const {
return "int: " + std::to_string(value);
}
std::string operator()(const std::string& value) const {
return "text: " + value;
}
};
int main() {
std::variant<int, std::string> value{42};
std::cout << std::visit(Describe{}, value) << '\n';
value = std::string{"hello"};
std::cout << std::visit(Describe{}, value) << '\n';
}
Result
int: 42 text: hello
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.