3 ms·
I might be missing something big but the "match (theSetting) {...}" example can be mapped to C++ as: switch(setting->tag) { case Str: // do something with
by lsh123 9y ago
I might be missing something big but the "match (theSetting) {...}" example can be mapped to C++ as:
switch(setting->tag) {
case Str:
// do something with setting->str
break;
case Int:
// do something with setting->n
break;
case Bool:
// do something with setting->b
break;
}
- hoytech 9y agoOne thing that a match method can provide is a compile-time check that you haven't forgotten to handle any cases of your variant.
- snowAbstraction 9y agoThe Clang C++ compiler will warn if the switch is not exhaustive.
- lsh123 9y agogcc will warn too
- humanrebar 9y agoFrom the article: """ Here be dragons, though, since we must always remember to: * Update tag whenever assigning a new value. * Only retrieve the correct type from the union (according to tag). * Call constructors and destructors at appropriate times for all non-trivial types. (string is the only one here, but you could imagine similar scenarios with others.) """ ...the last paragraph is the part that will almost surely trip a C++ newcomer up if they tried this out. The first to are (valid in my experience) complaints about maintenance mistakes that result in compiling programs but runtime errors.