Visitor in C++17
C++17 introduced a major change in the way we use the Visitor pattern with the addition of std::variant
to the standard library. The std::variant
template is essentially a “smart union:” std::variant<T1, T2, T3>
is similar to union { T1 v1; T2 v2; T3 v3; }
in that both can store a value of one of the specified types and only one value can be stored at a time. The key difference is that a variant object knows which type it contains, while with a union the programmer is wholly responsible for reading the same type as what was written earlier. It is undefined behavior to access a union as a type that differs from the one used to initialize it:
union { int i; double d; std::string s; } u; u.i = 0; ++u.i; // OK std::cout << u.d; // Undefined behavior
In contrast, std::variant
offers a safe way to store values of different...