This example shows an elegant way to deal with messages of different types in Rust. It has 4 variants and some variants have sub members that are only accessible if the enum is of that specific type. A similar pattern is also possible in TypeScript.
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
In C++ this would most likely compare to the following code.
struct Message
{
enum MessageType {QUIT, MOVE, WRITE, CHANGECOLOR} type;
union MessageContent
{
struct Move { int x; int y;} move;
std::string write;
std::tuple<int, int, int> changeColor;
} content;
};
However, this way isn't typesafe and memory management is going to become messy (e.g. making sure that string gets released if Message gets destructed if MessageType is WRITE). What is the best way to do this in modern C++?