Hacker News new | past | comments | ask | show | jobs | submit login

If you form a variant with multiple copies of the same type they will "collapse". E.g. std::variant<int, int> behaves like std::variant<int>.



Why would you want to list int more than once in a variant? I must be missing a use case here; my variants have consisted mostly of structs.


It's less that you specifically want an int/int case and more that you want consistent behaviour in a generic context - you might have some logic in a template that uses variant<int, T> and treats the int case specially (e.g. the int is an error code), but then you get a nasty surprise when it gets used in a case where T=int.

A common example is validation/result types, which often look like string (error message) or valid result. So e.g. you might have a username validator that returns Result<String, String> and then various other user creation validation things that return e.g. Result<String, EmailAddress> and in the end you compose them all together to get Result<String, User>. That's a very powerful style that has the advantages of exceptions (the "happy path" through the code is obvious and not obscured by all the failure handling) without their disadvantages ("magic" control flow, seemingly trivial refactors changing the behaviour). But it's less practical if you can't have Result<String, String> at the base level.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: