Value based overload resolution?

Paul Backus snarwin at gmail.com
Mon Nov 9 22:49:53 UTC 2020


On Monday, 9 November 2020 at 22:04:55 UTC, kdevel wrote:
> It appears to me that the overload resolution may depend on the 
> /value/ of the function argument. According to [1] the type of 
> 1 is int and that of 1L is long. Thus I would have expected 
> foo!int and foo!long being called in those cases.
>
> [1] https://dlang.org/spec/lex.html#integerliteral

As you've discovered, the types of integer literals (and literals 
in general) is somewhat fluid: the *default* type of `1` is 
`int`, but the compiler may infer a different type based on the 
value, or on the context in which the literal is used.

For example:

static assert(is(typeof([1, 2, 3]) == int[]));
int[] a = [1, 2, 3];
ubyte[] b = [1, 2, 3];

Perhaps even more confusingly, this also applies to manifest 
(enum) constants:

enum literal = [1, 2, 3];
static assert(is(typeof(literal) == int[]));
int[] a = literal;
ubyte[] b = literal;


More information about the Digitalmars-d-learn mailing list