https://issues.dlang.org/show_bug.cgi?id=24828
Issue ID: 24828
Summary: Generic parameter type is constrained by the type of
the default value
Product: D
Version: D2
Hardware: All
OS: All
Status: NEW
Severity: major
Priority: P1
Component: dmd
Assignee: [email protected]
Reporter: [email protected]
I've been hit by this regularly, having to fallback to overloading every time:
void foo(T)(T v = 0)
{
}
void main()
{
foo(); // ok
foo(1); // ok
foo("x"); // fail
}
Error: cannot implicitly convert expression `0` of type `int` to `string`.
For some reason, the compiler attempts to convert the default value to the type
of the argument and fails. This behavior renders default values of generically
typed parameters completely unusable.
Compare to C++, which does the right thing:
template<typename T = int> void foo(T a = 0)
{
}
int main()
{
foo();
foo(1);
foo("x");
return 0;
}
Note that C++ also requires a default type, while it shouldn't - the type can
be infered from the type of the default value. Anyway, adding the default type
in D doesn't help.
--