0Pricing
C++ Academy · Lesson

std::visit

Process variant alternatives.

Why std::visit?

Manually checking each alternative with get_if gets verbose. std::visit applies a callable to whichever type the variant currently holds, handling the dispatch for you.

#include <iostream>
#include <variant>
int main() {
    std::variant<int, double> v = 4;
    std::visit([](auto x){ std::cout << x << "\n"; }, v);
}

A Generic Lambda Visitor

A lambda taking auto works for every alternative if the body compiles for all of them. Here we print whatever type is active.

#include <iostream>
#include <string>
#include <variant>
int main() {
    std::variant<int, std::string> v = std::string("hi");
    std::visit([](const auto& x){ std::cout << x << "\n"; }, v);
}

All lessons in this course

  1. Scoped enum class
  2. Unions and Their Risks
  3. std::variant
  4. std::visit
← Back to C++ Academy