What's the rationale here? alias this and function arguments

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 10 03:36:21 PDT 2015


On Tue, 10 Mar 2015 10:27:13 +0000, John Colvin wrote:

> struct S {
> 	int a;
> 	this(T)(T v)
> 	{
> 		this = v;
> 	}
> 	void foo(T)(T v) {
> 		import std.conv : to;
> 		a = v.to!int;
> 	}
> 	alias foo this;
> }
> 
> void bar(S s){}
> 
> void main()
> {
> 	S s0;
> 	s0 = "3"; //OK S s = "3"; //OK bar("3"); //Not OK
> }
> 
> It would seem logical that the last one would work as well.
> What's the reasoning behind this?

autoconversion for function arguments can lead to bug-ridden code, and is 
a perfect way to disaster. besides, it's ambiguous. let's imagine that we 
have struct `S1`, which can be created from string too, and overload of 
`bar` as `void bar (S1 s)`. what `bar` compiler should choose for `bar
("3")`?

so compiler doesn't try to guess how to convert your function argument 
from valid constructor args to structs. this decreases the change to 
introduce a hard-to-detect bugs with implicit construction, and also 
increases the readability (imagine surprised reader that sees `bar("3")` 
in the code, but no `bar` overload that accepts string).

C++ tries to be "smart" here, and fails. D doesn't try to be smart, as 
it's not a compiler work to guess what you meant.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150310/e9144036/attachment.sig>


More information about the Digitalmars-d-learn mailing list