Why can't we make reference variables?
Jonathan M Davis
jmdavisProg at gmx.com
Thu Aug 30 09:58:11 PDT 2012
On Thursday, August 30, 2012 15:30:15 Tommi wrote:
> Yes, but to me the ambiguity of that example is in whether or not
> implicit deferencing of pointers has precedence over uniform
> function call syntax. Apparently it does, but it's not that
> obvious that it would.
It _can't_ work any other way, because there's no way to tell the compiler to
use the member function specifically. You can use the full import path for the
free function, so you can tell the compiler to use the free function. There's
no such syntax for member variables.
> struct MyStruct
> {
> int _value = 0;
>
> void increment()
> {
> ++_value;
> }
> }
>
> void increment(ref MyStruct* ptr)
> {
> ++ptr;
> }
>
> void main()
> {
> MyStruct* ptrMyStruct = new MyStruct();
>
> // Are we incrementing the pointer using UFCS or
> // are we calling the member function in MyStruct?
> ptrMyStruct.increment();
> }
For instance, if you do
increment(ptrMyStruct);
or
.increment(ptrMyStruct);
or if increment had a longer import path
path.to.increment(ptrMyStruct);
then you can tell the compiler to use the free function. But how would you do
that with the member function? You can't. So, there's really no other choice
but to choose the member function whenever there's a conflict. It also prevents
function hijacking so that something like var.increment() doesn't suddenly
start using using a free function instead of the member function when you add
an import which has an increment free function.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list