On Monday, 3 July 2017 at 13:53:45 UTC, Paolo Invernizzi wrote:
I've struct like that:
struct Foo {
int a_1; float a_2; string a_3;
string b_1; double b_2;
}
I would like to transparently access that like:
foo.a.first
foo.b.second = "baz";
with an helper like:
auto a(...) { ... }
auto b(...) { ... }
that can be used also in functions that are expecting it:
void worksOnA( .... ) { }
void worksOnB( .... ) { }
auto foo = Foo( ... )
foo.a.worksOnA();
foo.b.worksOnB();
But I'm struggling in finding a good way to do it...
Suggestions?
Thanks!
/Paolo
//https://dpaste.dzfl.pl/d59469c264b2
import std.algorithm : map, copy, equal;
import std.range : iota;
struct Foo {
int[3] a;
string[2] b;
}
ref T first(R : T[], T)(ref R x,){return x[0];}
ref T second(R : T[], T)(ref R x){return x[1];}
void worksOnA(R : int[N], size_t N)(ref R r) {
iota(1, N+1)
.map!(x => cast(int)x*2)
.copy(r[]);
}
void worksOnB(string[] r) { }
void main(){
auto foo = Foo();
foo.a.first = 1;
foo.a.second = 2;
assert(foo.a.first == 1);
assert(foo.a.second == 2);
foo.b.second = "test";
assert(foo.b.first == "");
assert(foo.b.second == "test");
foo.a.worksOnA();
assert(foo.a[].equal([2, 4, 6]));
}