Accessing private class members with tupleof
Jarrett Billingsley
jarrett.billingsley at gmail.com
Thu Jan 29 06:28:55 PST 2009
On Thu, Jan 29, 2009 at 3:51 AM, grauzone <none at example.net> wrote:
> Is it legal to access private members of a class using tupleof, when normal
> access would be illegal?
>
> It is not really clear from the D1.0 specification:
>
>> The .tupleof property returns an ExpressionTuple of all the fields in
>> the class, excluding the hidden fields and the fields in the base
>> class.
>
> Do private members count as hidden, or does the specification only consider
> the vtable and monitor fields as hidden fields? What exactly are "hidden
> fields" at all?
>
> It seems newer dmd versions allow you to access private members, while older
> versions raise a compile-time error.
>
> Here is an example to demonstrate the issue (for D1.0):
>
> ---file a.d
>
> module a;
>
> class Test {
> int a = 1;
> protected int b = 2;
> private int c = 3;
> package int d = 4;
> }
>
> ---file b.d
>
> module b;
>
> import a;
>
> int[] get(Test t) {
> int[] result;
> foreach (i, x; t.tupleof) {
> result ~= t.tupleof[i];
> }
> return result;
> }
>
> import std.stdio;
>
> void main() {
> //outputs [1,2,3,4]
> writefln(get(new Test()));
> }
>
Interesting. It used to be an error, but that made .tupleof useless
for all but the most basic aggregate types, since the compiler would
just error on anything with non-public fields. I would have expected
it to just give a tuple of the _public_ fields, but..
You could file an issue and see what Walter does or doesn't have to
say about it.
More information about the Digitalmars-d-learn
mailing list