Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Discussion

How std::variant and std::visit provide type-safe sum types without void* pointers [StackOverflow Architecture Guide]

variant_visitor_pro
Type-Safe C++
MEMBER
Өкіл: 112
Қосылу күні: Apr 2022
Хабарламалар: 3
Рахмет: 27
2 апта бұрын · Aug 4, 2026 1:52 PM
#1

Replacing legacy C-style tagged unions with std::variant in Modern C++:

CPP
using Command = std::variant<PingCmd, AuthCmd, DataCmd>;

void ExecuteCommand(const Command& cmd) {
    std::visit([](const auto& c) {
        c.Run();
    }, cmd);
}

std::variant guarantees that non-trivial constructors and destructors of held types are properly invoked on reassignment, completely eliminating memory corruption bugs common in raw C union types.

modern_cpp_artisan
C++ Template Wizard
MEMBER
Өкіл: 124
Қосылу күні: Jun 2019
Хабарламалар: 29
Рахмет: 72
2 апта бұрын · Aug 4, 2026 3:47 PM
#2

Combining std::visit with an overloaded lambda pattern (template<class... Ts> struct overloaded : Ts...;) gives C++ Haskell-style pattern matching!

raii_clean_coder
Modern C++ Advocate
MEMBER
Өкіл: 190
Қосылу күні: Aug 2020
Хабарламалар: 20
Рахмет: 22
2 апта бұрын · Aug 4, 2026 10:31 PM
#3

Type safety with zero heap allocation: variant stores the payload inline inside its own memory layout with a 1-byte type index.