4 ms·
The printing was only a simple example. A less contrived example would be to evaluate an AST. E.g. you would want the '+' operator to do different things for st
by any1 9y ago
The printing was only a simple example. A less contrived example would be to evaluate an AST. E.g. you would want the '+' operator to do different things for strings and numbers.
Also, your visit function does not do exactly the same thing as the author's example. The author's example also prints the type's name. How would you do that without making the visitor cases explicit?
- clishem 9y ago> How would you do that without making the visitor cases explicit? See my edit. std::visit([](auto &&val) { std::cout << typeIdxToString[typeid(val)] << val; }, var); > E.g. you would want the '+' operator to do different things for strings and numbers. Then overload the '+' operator, no need to put all that in the visitor lambda.
- any1 9y agoYes, this would work. I can see that variant may prove useful for the case that you present, but it is much less elegant for the usecase which the author tries to present. Edit: Replaced second "useful" with "elegant"