Developer knowledge network · moderated exchange

UnreliableCode コミュニティ

開発者リサーチ、リバース エンジニアリング、コーディング コミュニティ

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.