Skip to content

One Event with Several Alternatives

The Course
•
35 min study

A batch is a sequence of events, and a std::vector holds elements of one type. Create, Adjust and Rename are three types. You need one type whose values can be any one of the three, and nothing else.

There are two classic answers. Inheritance gives each event a common base class and stores std::unique_ptr<EventBase> in the vector: every event becomes a separate heap allocation, and the set of event kinds is open, so any file can add a new one. std::variant<Create, Adjust, Rename> is the other answer. It is a value type that stores exactly one of the listed alternatives inside itself, with no heap allocation of its own, and its set of alternatives is closed: it is written in one place and the compiler knows all of it. For a wire format with three documented operations, closed is exactly right. Include <variant> to use it.

Predict and run

Predict before running C++
#include <iostream>
#include <variant>

struct Create { int id; };
struct Adjust { int id; int delta; };
using Event = std::variant<Create,Adjust>;

int main() {
    Event event = Adjust{2,-3};
    if (const auto *adjust = std::get_if<Adjust>(&event)) { std::cout << adjust->delta << "\n"; }
    std::cout << std::holds_alternative<Create>(event) << "\n";
    return 0;
}
Check your prediction
Text
-3
0

event holds an Adjust, its active alternative. std::get_if<Adjust>(&event) returns a pointer to that Adjust because it is active, so the if body runs. std::holds_alternative<Create> asks a yes-or-no question and gets false, which std::cout prints as 0. Change the initializer to Create{2} and predict again: get_if now returns nullptr, the if body is skipped, and the second line prints 1. Nothing invents an adjustment that was never there.

What a variant holds

A variant always holds exactly one alternative. It knows which one through a small stored discriminator, and index() reports its zero-based position in the type list. Assigning a value of a different alternative destroys the old one and constructs the new one in the same storage. A type that announces its own construction and destruction makes this visible:

Switching the active alternative C++
#include <iostream>
#include <string>
#include <variant>

struct Loud {
    std::string name;
    explicit Loud(std::string text) : name(std::move(text)) { std::cout << "make " << name << "\n"; }
    ~Loud() { std::cout << "drop " << name << "\n"; }
};

int main() {
    std::variant<int, Loud> value = 7;
    std::cout << "index " << value.index() << "\n";
    value.emplace<Loud>("Bolts");
    std::cout << "index " << value.index() << "\n";
    value = 3;
    std::cout << "index " << value.index() << " holds " << std::get<int>(value) << "\n";
    return 0;
}
Text
index 0
make Bolts
index 1
drop Bolts
index 0 holds 3

emplace<Loud> constructs the new alternative in place, so no temporary Loud is made and moved. Assigning 3 destroys the Loud, which is why drop Bolts appears before the last line, not at the end of main. This is RAII applied to a sum type: the variant owns whichever alternative is active and runs the right destructor without you tracking it. A default-constructed variant holds a value-initialized first alternative, so put a cheap, meaningful type first, or use std::monostate as an explicit empty alternative.

Its size is roughly the largest alternative plus the discriminator, rounded for alignment. The exact number is implementation-defined, so do not write code that depends on it.

Three ways to look inside, and which to trust

  • std::holds_alternative<T>(v) answers a question and never fails.
  • std::get_if<T>(&v) returns a pointer to the alternative or nullptr. The if (auto* p = ...) form keeps the pointer's scope as small as the check that makes it valid.
  • std::get<T>(v) returns a reference and assumes you are right. If T is not active it reports failure by throwing std::bad_variant_access. This course compiles with exceptions disabled, so in practice a wrong get stops the program. Use it only when you know which alternative is active: right after a check, or, as the example above does on its last line, right after assigning that alternative.

The pointer from get_if borrows the variant's storage, and that storage is reused when the alternative changes:

C++
std::variant<int, std::string> value = 7;
int* number = std::get_if<int>(&value);
value = std::string("Read"); // The int is destroyed; the storage now holds a string.
std::cout << *number;        // Undefined behavior: number points at a dead int.

The compiler cannot warn about this, and it may even print 7 by accident. Treat a get_if pointer like any other borrowed pointer: use it before the next change to the variant, then let it go out of scope.

Construct alternatives explicitly

A variant converts from a value by picking the alternative it best matches, using rules that are subtle and changed in C++20. Instead of reasoning about them, name the alternative you mean: Event{Adjust{2, -3}}, std::string("Read") or emplace<T>(...). Explicit construction reads clearly and cannot change meaning when someone adds an alternative later. Note also that two identical alternatives such as std::variant<int, int> cannot be told apart by type, so get<int> will not compile; give each operation a distinct struct instead.

Practice

Exercise

Your turn

A report field is using Field = std::variant<int, std::string>;. Write std::string describe(const Field& field) using get_if, so that it returns number 7 for an int and text Read (4 chars) for a string. In main, start with the text Read, print the description and the index, then assign 7 and print both again:

Shell
text Read (4 chars) at index 1
number 7 at index 0
Your workspace C++
#include <iostream>
#include <string>
#include <variant>

using Field = std::variant<int, std::string>;

int main() {
    Field field = std::string("Read");
    // Describe the field, then assign 7 and describe it again.
    return 0;
}
Hint 1: the idea

Ask for each alternative in turn. Exactly one get_if returns a non-null pointer.

Hint 2: a first step

Start with if (const int* number = std::get_if<int>(&field)) { return "number " + std::to_string(*number); }.

Show one solution
Run the solution C++
#include <iostream>
#include <string>
#include <variant>

using Field = std::variant<int, std::string>;

std::string describe(const Field& field) {
    if (const int* number = std::get_if<int>(&field)) {
        return "number " + std::to_string(*number);
    }
    if (const std::string* text = std::get_if<std::string>(&field)) {
        return "text " + *text + " (" + std::to_string(text->size()) + " chars)";
    }
    return "unknown";
}

int main() {
    Field field = std::string("Read");
    std::cout << describe(field) << " at index " << field.index() << "\n";
    field = 7;
    std::cout << describe(field) << " at index " << field.index() << "\n";
    return 0;
}
Text
text Read (4 chars) at index 1
number 7 at index 0

Each pointer lives only inside its own if, so it cannot outlive the assignment that replaces the string. Notice the return "unknown"; at the end: the compiler needs it, and it is also a weakness. Add a double alternative to Field and this function still compiles, quietly describing every double as unknown. The next lesson replaces the chain of checks with std::visit, which turns that forgotten case into a compile error.

Was this article helpful?

Your response is saved on this device.