October 23 [Issue 24828] New: Generic parameter type is constrained by the type of the default value | ||||
---|---|---|---|---|
| ||||
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: nobody@puremagic.com Reporter: maxsamukha@gmail.com 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. -- |
Copyright © 1999-2021 by the D Language Foundation