From: brianjparker (brianjparker_at_[hidden])
Date: 2002-02-19 23:50:17
--- In boost_at_y..., "Fernando Cacciola" <fcacciola_at_g...> wrote:
> >template<typename T1, typename T2>
> >auto min(T1 t1, T2 t2)
> > if (t1 < t2) return t1;
> > else return t2;
> This example won't behave as intended.
> The type of foo() (the return type), is determined at runtime, not
> 'auto' here would actually mean 'boost::any', but we are
> compile-time type deduction, not a dynamic typing.
> This example, however, pops up an important thing:
> The type of the result of a function can ONLY be determined by its
> expression. As I pointed out, it cannot be determined by the
> arguments becuase there is no reason why a function should return a
> associated with the type of its arguments.
> But a return expression can only have a fixed known-at-compile-time
> doesn't matter which sort of type deduction is used, the type must
> otherwise, we are talking about true dynamic typing as in 'min'
> we don't want that.
> Therefore, 'auto' for a return type will allow implicit conversions
> implicit type.
> The only case when it will guarantee no implicit conversions is
> single auto variable is used for the return expresion:
> auto foo()
> auto r = some();
> return r ;
> If the return expression includes anything else, including more
> auto variables, it could involve an implicit conversion.
> auto foo()
> auto a = someA();
> auto b = someB();
> return choose_one() ? a : b ; // posible implicit conversion
> Just as I wear the hat of 'don't use implicit conversions', I would
> hat of "don't use auto return types" if they were allowed.
> I do however, support the 'auto' for variable declaration because
> not a conversion involved even though the type is implicit.
The auto in the min() function example would be a well-defined
compile-time-deduced type- it would be the common conversion type of
all return paths (which is just extended version of the type
conversion rules of operator ?: ). A min function that takes
arbitrary arguments *must* have as a return type the common
conversion type of the arguments, so one way or another you will need
to deduce this common type and cast the arguments to it; "auto" (or
my preferred template<typename R> syntax) just makes this convenient
As you say, in the case where there is a single return path, or all
return paths return the same type then the function return will be of
that type; and the case where different convertible types are
returned then one or more of them will involve an implicit conversion
to the common conversion type (just like ?:).
This is a feature- computing the common conversion type of several
types is essential for writing fully generic functions that take
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk