Bug 16467 – templated function default argument take into account when not needed
Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2016-09-05T12:58:36Z
Last change time
2018-01-27T23:33:38Z
Assigned to
No Owner
Creator
Lodovico Giaretta
Comments
Comment #0 by lodovico — 2016-09-05T12:58:36Z
T identity(T)(T t = 0)
{
return t;
}
void main()
{
int i = identity(); // as expected
string s = identity("hello"); // error: cannot implictly converto (0)
// of type int to string
}
I would expect the default value to be completely discarded when the user supplies a value.
Comment #1 by issues.dlang — 2016-09-06T11:58:36Z
I suspect that this will be declared to be "not a bug." While, I can understand your reasoning, the problem is that when you pass a string to your identity function, IFTI instantiates it with string. It's only called _after_ the function has been compiled, and the default argument does not work with the type in question.
Remember that templatizing a function directly is just shorthand for declaring an eponymous template that it's a function. So, this would be equivalent to what you declared:
template identity(T)
{
T identity(T t = 0)
{
return t;
}
}
And if the template is instantiated with string, then the default argument is not valid. Also consider the case where you do
auto result = identity!string();
It's exactly the same template instantiation as identity("hello"), but it would need the default argument, which is the wrong type.
Comment #2 by lodovico — 2016-09-07T15:54:40Z
(In reply to Jonathan M Davis from comment #1)
> [...]
Yeah, I understand the reasons. I decided to put this here as an enhancement request because there are cases in which it's *very* ugly.
In my use case I have a default callback parameter. If I choose a default that is not @safe pure @nogc nothrow, my users will get an error when their callbacks are, because my default does not fit their type.
I'm forced to add an overload without that parameter, which kinda defeats the purpose of default parameters and, most important, doubles the number of overloads needed. I had a case in which four overloads became eight because of this.
But of course this may not be a compelling enough reason, especially if the needed changes would be big or have bad side effects. In that case, feel free to close as WONTFIX or INVALID.