Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties and ref return values in D

Tags:

properties

ref

d

Testing the following in D

import std.stdio;

struct S
{
    int _val;
    @property ref int val() { return _val; }
    @property void val(int v) { _val = v; writeln("Setter called!"); }
}

void main()
{
    auto s = S();
    s.val = 5;
}

yields "Settter called!" as the output.

What rule does the compiler use to determine whether to call the first or the second implementation?

like image 220
user541686 Avatar asked Mar 04 '26 17:03

user541686


1 Answers

Here you are providing two @property methods, one accepts an argument, the other does not. When doing s.val = 5;, what you're actually doing is s.val(5), but as val is a @property you can write it as a property rather than a method call (see http://d-programming-language.org/function.html#property-functions). From s.val(5) the compiler can do standard overload resolution - see http://d-programming-language.org/function.html#function-overloading.

like image 67
Robert Avatar answered Mar 07 '26 09:03

Robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!