alias tuples?
Reiner Pope
some at address.com
Sun Oct 14 01:24:06 PDT 2007
Janice Caron wrote:
> We've got value tuples, and we've got type tuples. Could we also have
> alias tuples?
>
> Here's what I mean. Right now I can do:
>
> struct A
> {
> X x;
> Y y;
> Z z;
>
> mixin Serialize!(x,y,z);
> }
> A a;
>
> template Serialize(alias x,alias y,alias z)
> {
> void serialize()
> {
> x.serialize();
> y.serialize();
> z.serialize();
> }
> }
>
> where the types X, Y and Z all have a serialize() function (and so on
> recursively for every object in need of serialization). Now it seems
> to me, if I wanted to make Serialize!() variadic, I'd need not a value
> tuple, nor a type tuple, but an "alias tuple". I'd want to be able to
> write something like:
>
> struct A
> {
> X x;
> Y y;
> Z z;
>
> mixin Serialize!(this.aliastupleof); /* expands to (x,y,z) */
> }
> A a;
>
> template Serialize(alias T...)
> {
> void serialize()
> {
> foreach(a;T)
> a.serialize();
> }
> }
>
> Of course this won't work right now. The template won't compile
> because (alias T...) has no meaning, and even if it did, structs don't
> have an aliastupleof property.
>
> Thoughts?
You can sort of fake it. You could write your first example as
struct A
{
int x = 1;
int y = 2;
int z = 3;
void serialize()
{
.serialize(this.tupleof); // or .serialize(x, z); if you want
}
}
void serialize(T...)(T t)
{
foreach (t2; t)
typeSpecificSerialize(t2); // or t2.serialize(), but that won't
work with int
}
void typeSpecificSerialize(T)(T t)
{
writefln("%s: %s", T.stringof, t); // or whatever you want
}
---
But you don't get the variable names this way. If you want that, you can
do the following, although you lose the variadic bit:
void serialize(T)(T t)
{
foreach (i, t2; t.tupleof)
{
writefln("%s: [%s]", T.tupleof[i].stringof, t2);
}
}
struct foo
{
int a = 1;
int b = 2;
}
void main()
{
foo f;
serialize(f);
}
---
I hope that helps, although it's not what you asked for. ;)
-- Reiner
More information about the Digitalmars-d
mailing list