return type and templates

Andrea Fontana nospam at example.com
Fri Nov 22 05:43:47 PST 2013


On Friday, 22 November 2013 at 12:29:25 UTC, Jonathan M Davis 
wrote:
> On Friday, November 22, 2013 11:50:57 Andrea Fontana wrote:
>> I just mean:
>> 
>> int t = s.value;  // Means  int t = s.value!int;
>> 
>> If there's a problem with template instantiatio is the same we
>> have now.
>> Now I have to write:
>> 
>> int t = s.value!int;
>> 
>> so if there's a problem with !int, it's just like now.
>> 
>> It's just a syntactic sugar, no new feature... Am I wrong?
>
> Again, how is the compiler supposed to have any clue that you 
> want to
> instantiate value with int in the case of
>
> int t = s.value;
>
> The left-hand side of the expression has no impact on the type 
> of the right-
> hand side, and you have not given the compiler any information 
> as to what
> template argument should be given to value. s.value(3) only 
> works because
> you've given value a function argument from which the 
> corresponding template
> argument can be inforred. With s.value, you've given no 
> indication whatsoever
> as to what value should be instantiated with.
>
> If you want a default template argument, then give it one. e.g.
>
> @property auto value(T = int)() if (is(T == int)) { return 
> _intValue; }
>
> But I don't know how you expect the compiler to have any clue 
> what type value
> should be instantiated with when you haven't given it any 
> template arguments
> and there are no function arguments to infer the template 
> arguments from -
> especially when this what the compiler really sees
>
> template value(T)
>     if(is(T == int))
> {
>     @property auto value() { return _intValue; }
> }
>
> and it doesn't even look at the template constraint, let alone 
> the contents of
> the template, until you attempt to instantiate the template. 
> And it's not
> going to be able to try and instantiate the template without 
> having any
> template arguments.
>
> - Jonathan M Davis


I don't know how compiler works internally. (is there any 
documentation other than the comments and code itself?)

So probably I'm wrong about what compiler knows and not.
Parsing this:

int t = s.value;

I assumed that it knows - when is trying to instatiate s.value 
template - that "s.value" is part of an assignment and that it 
will be assigned to an int. So if template argument is missed and 
s.value returns T, T should be int. But if I understand your 
answer, right-hand side can't see left-hand side.

By the way the default value doesn't works for me because in my 
library I have to choose from many different template. So i have 
to do every time:

int i = asd.value!int;
string s = asd.value!string;
long l = asd.value!long;

and so on... and i hoped I could do:

int i = asd.value;
string s = asd.value;
long l = asd.value;

Ok, if it's impossible, never mind :)


More information about the Digitalmars-d-learn mailing list