Bug 24828 – Generic parameter type is constrained by the type of the default value

Status
RESOLVED
Resolution
DUPLICATE
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2024-10-23T09:30:44Z
Last change time
2024-10-23T10:20:56Z
Assigned to
No Owner
Creator
Max Samukha

Comments

Comment #0 by maxsamukha — 2024-10-23T09:30:44Z
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.
Comment #1 by dkorpel — 2024-10-23T10:20:56Z
*** This issue has been marked as a duplicate of issue 21917 ***