literals

Steven Schveighoffer schveiguy at yahoo.com
Sun Mar 28 12:46:55 PDT 2010


On Sun, 28 Mar 2010 14:29:52 -0400, so <so at so.do> wrote:

>> What you want is implicit function template instantiation based on the  
>> return type.  D doesn't do that, it doesn't even allow overloading  
>> based on the return type.  However, you can infer the return type using  
>> auto:
>>
>> auto inv(T)(T m)
>> {
>>     return 1.0/m;
>> }
>>
>> -Steve
>
> Hello!
>
> I guess, i am unable to express myself.
>
> In code :
>
> T inv(T)(T m) {
> 	return 1.0/m;
> }
>
> If we forget the rules of default literals that C derived languages  
> have, just for a second.
>
> And enforce our own little rule.
> - no implicit casts
>
> With this in mind this code says; i gave you T, give me T in return,  
> perfectly clear i guess?
> Now when you call the function with a floating point, real, double,  
> float..., you will get what you asked for.
> Now what about other types? Say you call it with a non floating type,  
> when compiler tries to divide the first thing
> it will encounter that one of two elements of the operation is a  
> non-float, since we enforced a rule, it gives warning or error.

What you are asking for is a template instantiation that depends on  
instantiating itself.  How about a function like this?

void foo(int x);

T inv(T)(T m) {
    foo(m);
    return 1.0/m;
}

How do you know what type to use for T?  It's simple when you make inv a  
one-liner, there is only one thing to look at.  But as you start making  
the function more complex, then it's impossible to tell what the user  
actually wants.   In this instance, T must be implicitly convertable to  
int, but also must be a floating point type.  Clearly there is an error  
here, but where is it?  This is called ambiguity, and to avoid it, the  
compiler makes a decision, right or wrong, based on the literal used to  
call the function.  It expects you, the user, to help out when it doesn't  
make the right one.  I don't think it's too much to ask.  It's simply a  
tradeoff between being an all-powerful oracle-like compiler and being a  
simple-to-write compiler.

What the compiler sees when deciding to instantiate is this:

T inv(T)(T m) {...}

And it makes a decision.

If you have a problem with writing inv(5.0) instead of inv(5), then maybe  
D just isn't for you.

-Steve



More information about the Digitalmars-d mailing list