Accessing part of a struct in an easy way

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 3 10:30:51 PDT 2017


hOn 07/03/2017 10:13 AM, Paolo Invernizzi wrote:

 > It's not exactly the same, as first and second should be struct with
 > partial fields from Foo, of different types.

I had difficulty understanding the requirements. For example, it's not 
clear whether you want the literal "first" and "second" names.

If you want to magically use part of a struct as a separate type, it's 
impossible in a strongly typed language like D. However, you have 
low-level options that allow you to lay data almost in any way you want.

Obviously, if you have access to Foo's source and it's feasible to 
change it, you can do this:

struct Foo {
     A a;
     B b;
}

Assuming that it's not possible, you can cast addresses of parts of the 
struct as addresses of other types. Compiles but not tested:

struct Foo {
     int a_1; float a_2; string a_3;
     string b_1; double b_2;
}

struct A {
     int a_1; float a_2; string a_3;
}

struct B {
     string b_1; double b_2;
}

auto ref a(ref Foo foo) {
     return *cast(A*)&foo.a_1;
}

auto ref b(ref Foo foo) {
     return *cast(B*)&foo.b_1;
}

void worksOnA(ref A a) {
}

void worksOnB(ref B b) {
}

void main() {
     auto foo = Foo();
     foo.a.worksOnA();
     foo.b.worksOnB();
}

Ali



More information about the Digitalmars-d-learn mailing list