Add support implicit conversion between types
Jonathan M Davis
jmdavisProg at gmx.com
Fri Sep 6 10:48:45 PDT 2013
On Friday, September 06, 2013 12:33:05 ilya-stromberg wrote:
> Do you have any plans to support implicit conversion between
> types?
>
> I have some code like this:
>
> struct Foo
> {
> this(int i)
> {
> //do something useful
> }
> }
>
> void bar(Foo f)
> {
> //do something else
> }
>
> void main()
> {
> Foo f = 5;//works
>
> bar(f);//works
>
> bar(Foo(5));//works
>
> bar(5);//Error: function app.bar (Foo f) is not callable using
> argument types (int)
> }
>
> So, D can't use constructor to convert "int" to "Foo" implicitly.
> Can we add "implicit" keyword to allow do this:
>
> struct Foo
> {
> implicit this(int i)
> {
> //do something useful
> }
> }
>
> C++ allows this, but have "explicit" keyword.
> C# doesn't allow this, but have operator overloading for both
> implicit and explicit cases.
Personally, I think that this is opening a whole can of worms that should
never be opened. alias this already causes enough trouble for stuff like
templates (primarily because it becomes far too easy to pass a template
constraint and yet fail to work in the actual code). It's ultimately way
cleaner and far less bug-prone to disallow this sort of implicit conversion,
especially when so much D code is generic code.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list