alias this constructor

Shachar Shemesh shachar at weka.io
Sun Mar 25 03:24:35 UTC 2018


On 25/03/18 04:51, Jonathan M Davis wrote:
> On Sunday, March 25, 2018 00:47:20 Dave Jones via Digitalmars-d wrote:
>> struct Foo
>> {
>>       int x;
>>       alias x this;
>> }
>>
>> Foo f = 12; // error
>>
>> Foo foo;
>> f = 12;     // this is OK
>>
>> any reason why the first cant be allowed?
> 
> Because it was deemed to cause too many problems. C++ code can have quite a
> few problems related to all of the implicit conversions it allows with stuff
> like constructing objects. Walter decided that D would be better off if it
> did not allow such conversions, and as such, D is much pickier about
> implicit conversions in general.

That's a good reason to disallow assignment from int to Foo. I see zero 
sense in allowing assignment and disallowing construction.

*****

Technically, I understand the mechanisms at play here. During 
construction, this is a Foo object, and it has no construction from int. 
During assignment, we are allowed to convert a Foo lvalue to a Foo.x 
(int) lvalue, and that gets assigned.

Despite understanding the mechanics, I find the end result surprising 
and unexpected. D makes it damn easy to implicitly expose an inner 
member, and much more difficult to actually do this safely (you have to 
create a property and then alias this that property).

If I'd be building C++ today, I'd replace the "explicit" keyword with 
"implicit" (i.e. - still allow single var constructors to become 
implicit conversion ops, but make that transformation an opt-in rather 
than an opt-out feature). I think that would have been a much better 
approach than what D took.

Shachar


More information about the Digitalmars-d mailing list