Return type of std.algorithm.map

James Fisher jameshfisher at gmail.com
Fri Jul 8 09:46:02 PDT 2011


On Fri, Jul 8, 2011 at 4:49 PM, Steven Schveighoffer <schveiguy at yahoo.com>wrote:

> On Fri, 08 Jul 2011 11:08:14 -0400, James Fisher <jameshfisher at gmail.com>
> wrote:
>
>  On Fri, Jul 8, 2011 at 4:06 PM, James Fisher <jameshfisher at gmail.com>
>> wrote:
>>
>>>
>>> So ... stuff works, but I'm not really sure why one uses function
>>> templating and the other uses return type inference.  Any answers?
>>>
>>
>>
>> ... Wait, brain malfunction; I think I do understand.  The type is
>> inferable
>> purely from the function definition in the latter case.
>>
>
>
> Yes, the return type is determined by the return statement in the function
> itself.  Note that it would be an error to have two different return types
> that compiled into the same function.  A frequent use of auto is when the
> return type could be different based on template parameters to the function,
> or version statements.  In these cases, effectively there is only one return
> type, because only one return statement gets compiled.
>
> The reason your getSquares(T)() *call* doesn't work is because the compiler
> first must instantiate the template, and it doesn't have enough information
> to do so.  Remember that a function template like this:
>
> T getSquares(T)() {...}
>
> is equivalent to this:
>
> template getSquares(T)
> {
>   T getSquares() {...}
> }
>
> So in fact, the compiler cannot evaluate the inner part of the template
> until it knows what T is.  However, there is a special feature called
> implicit function template instantiation (IFTI) which allows the compiler to
> infer the values of T from the function call being made.  This means the
> types of arguments to the function can be used to infer the template
> parameters.  This *only* works for template functions or templates that can
> be reduced to template functions.
>
> So for example:
>
> T foo(T)(T t) {return t;}
>
> you can call this function via:
>
> foo(1);
>
> And T will implicitly be assigned int.
>
> But since your getSquares function takes no parameters, IFTI cannot be
> used.  Note that the return type does NOT play a role in IFTI.
>
> However, you can still use getSquares, just specify the template parameter
> explicitly:
>
> auto sq = getSquares!int();
>
> Another option is to give a default value for T:
>
> T getSquares(T = int)() {...}
>
> -Steve
>

This all makes sense.  Thanks for the comprehensive explanation. :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20110708/def83f45/attachment.html>


More information about the Digitalmars-d-learn mailing list