On Monday, 23 May 2016 at 07:03:08 UTC, chmike wrote:
On Saturday, 21 May 2016 at 17:32:47 UTC, dan wrote:

(This effect could be simulated by making my_var into a function, but i don't want to do that.)

May I ask why you don't want to do that ?

In D you can call a function without args without ().

So if you write

private int my_var_ = 4; // where 4 is the default initialization value
@property int my_var1() { return my_var_; }
final int my_var2() { return my_var_; }
int my_var3() { return my_var_; }

int x = obj.my_var1;
x = obj.my_var2;
x = obj.my_var3;


my_var3 is virtual so I guess you get the overhead of a virtual method call which is probably not what you want.

my_var2 can't be overriden and if it doesn't itself override a method with a same name in a base class the compiler may optimize its call by inlining it. It's like a static method with 'this' passed as argument.

I'm not fully sure about my_var1. I'm still a beginner, but I think the compiler will optimize it into inlined instruction if it can as for my_var2.

Making the user accessing the member variables directly may look like it's more efficient, but it's bad API design because you can't change the class implementation affecting my_var_ without breaking the API. The D way enforces good programming and API design and optimizes as much as possible.

Thanks Ch Mike for your reply and explanation, and the
further information about calling functions.

Thanks also to the other Mike, to Daniel for the interesting
union technique, and to Meta for further elaboration.
Daniel's union technique is pretty close to what i was
asking for.

Now, since you explicitly ask me 'why you don't
want to do that', i should answer.  But my answer
won't be nearly as good as your analysis and
explanation, nor as good as any of the other replies.  :(

Just aesthetically, i'd like to refer to the
variable within the class and outside the class
with exactly the same symbol.

But with all the ideas presented in the prior
discussion, i can get pretty close so it would
be a ridiculous point for me to complain about.

Thanks again for your help!

dan

Reply via email to