Messing with betterC and string type.

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Sep 7 13:58:41 UTC 2018


On Thursday, September 6, 2018 11:09:34 AM MDT SrMordred via Digitalmars-d 
wrote:
> > void foo(string s) {}
> >
> > foo("this");
> >
> > won't compile, since it won't make a String out of that
> > immutable(char)[] literal without an explicit initialization of
> > some sort.
>
> //cannot pass argument "this" of type string to parameter String s
> iep, this seems a real problem. ;/

It's one of those decisions that was made to prevent certain classes of bugs
- which it does do - but then it gets very annoying in situations like this.
Whether it's better to have implicit construction and risk the bugs that
come with it or whether it's better to avoid the bugs and thus not have
implicit construction is debatable.

What probably makes it particularly bad for C++ though is that C++ will
(IIRC) do up to three conversions when calling a function. So, depending on
what types you have available for a piece of code, you could end up with
nonesense like

void foo(String S) { ... }

foo(42);

compiling (e.g. if there were a type that could be explicitly constructed
from int, and it in turn implicitly converted to String - or if that type
implicitly converted to a const char*, and String could be implicitly
constructed from it). One of the tactics to reduce the problems in C++ is to
make constructors explicit as much as possible to reduce the number of
possible conversions, but if you have enough implicit constructions and/or
conversions in place, it can get pretty nasty.

If we had implicit construction in D but only allowed one level of
conversion (e.g. String could be implicitly constructed from a
const(char)[], but a type that implicitly converted to const(char)[]
couldn't be used to construct a String), maybe it would be sane enough. I
don't know. This is one of those situations where doing what many folks
would consider to be more user-friendly can quickly introduce subtle and
annoying bugs - hence why D was conservative about it. And honestly, the
implicit conversions that we already have create enough problems with stuff
like templates as it is without adding in stuff like implicit construction.
If only we could somehow have all of the useful implicit
conversion/construction stuff without actually getting subtle bugs out of
the deal... :|

In any case, all you have to do is just be explicit about construction,
which an be somewhat annoying but for the most part isn't a big deal. And as
Kagamin pointed out, you can always create a helper function with a really
short name to call the constructor if you want to.

It wouldn't surprise me if someone writes a DIP on implicit construction at
some point, but at least for now, for better or worse, we get to live
without it.

- Jonathan M Davis





More information about the Digitalmars-d mailing list