Template return values?

Jonathan M Davis jmdavisProg at gmx.com
Wed Dec 5 16:31:39 PST 2012


On Thursday, December 06, 2012 01:06:33 Dmitry Olshansky wrote:
> > To know what on earth you're suposed to do with the variable. If it's a
> > type that you can't handle, then yes, you'd probably have to throw an
> > exception, but you generally use a Variant because you need to be able to
> > return multiple types from the same function, and each is going to be
> > treated differently, otherwise you could have just used a common type to
> > begin with.
> 
> This is a sort of case against Varaint at large.

Honestly, the only use cases for Variant that I would consider valid would be 
those where you _can't_ use static typing in any sane way - the places where 
you're effectively forced to use a union (where a Variant is a better union). 
If you can reasonably solve the problem by using a common type, then I'm 
completely against using Variant for it.

Pretty much the only kind of situation that I remember running into where I 
would consider Variant to be a good solution is one where you literally have 
to return a type from a function where you can't know that type at compile 
time, and there is no common type to use. And the only time that I recall 
running into that recently was in writing a lexer (the values of literals 
ended up having to be put in a variant type). There are obviously other use 
cases besides that (database-related stuff and spreadsheets like you mentioned 
are other possibilities), but they are extremely rare in my experience. In 
almost all cases, you can and should know the type at compile time, in which 
case, using Variant makes no sense.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list