0Pricing
C++ Academy · Lesson

std::visit

Process variant alternatives.

std::visit is a free C++ Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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);
}

Returning a Value

std::visit can return a value. Every branch must return the same type.

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

Per-Type Behavior with if constexpr

To act differently per type inside one generic lambda, combine if constexpr with std::decay_t and std::is_same_v.

#include <iostream>
#include <string>
#include <variant>
#include <type_traits>
int main() {
    std::variant<int, std::string> v = 5;
    std::visit([](const auto& x){
        using T = std::decay_t<decltype(x)>;
        if constexpr (std::is_same_v<T, int>) std::cout << "int " << x << "\n";
        else std::cout << "str " << x << "\n";
    }, v);
}

A Struct Visitor

You can also write a struct with multiple operator() overloads, one per type. The compiler picks the matching overload.

#include <iostream>
#include <string>
#include <variant>
struct Printer {
    void operator()(int i) const { std::cout << "int " << i << "\n"; }
    void operator()(const std::string& s) const { std::cout << "str " << s << "\n"; }
};
int main() {
    std::variant<int, std::string> v = std::string("yo");
    std::visit(Printer{}, v);
}

The Overloaded Idiom

A popular helper combines several lambdas into one visitor. Each lambda handles a specific type.

#include <iostream>
#include <string>
#include <variant>
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main() {
    std::variant<int, std::string> v = 8;
    std::visit(overloaded{
        [](int i){ std::cout << "i=" << i << "\n"; },
        [](const std::string& s){ std::cout << "s=" << s << "\n"; }
    }, v);
}

Exhaustiveness

A visitor must handle every alternative, or the code fails to compile. This compile-time check prevents forgetting a case.

Visiting and Mutating

If you pass the variant by non-const reference, the visitor can modify the stored value in place.

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

Multiple Variants

std::visit can take several variants at once; the visitor then receives one argument per variant.

#include <iostream>
#include <variant>
int main() {
    std::variant<int, double> a = 2;
    std::variant<int, double> b = 3.0;
    auto sum = std::visit([](auto x, auto y){ return x + y; }, a, b);
    std::cout << sum << "\n";
}

Choosing a Visitor Style

Use a generic auto lambda for uniform handling, the overloaded idiom for clean per-type logic, and a struct visitor when behavior is reusable across call sites.

Visit vs get_if

get_if is fine for a single quick check, but std::visit scales: it enforces exhaustiveness and keeps all per-type logic in one place.

Quick Check

Check your understanding of std::visit.

Recap

You learned std::visit:

  • Dispatches a callable to the active alternative.
  • Use generic lambdas, if constexpr, struct visitors, or the overloaded idiom.
  • Visitors must be exhaustive (compile-time check).
  • Can return values and visit multiple variants together.

Frequently asked questions

Is the “std::visit” lesson free?

Yes — the full text of “std::visit” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “std::visit”?

Process variant alternatives. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “std::visit” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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