Array of templated classes or structs
TheFlyingFiddle via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Oct 24 11:40:01 PDT 2015
On Saturday, 24 October 2015 at 18:29:08 UTC, TheFlyingFiddle
wrote:
> Variant[] array;
> array ~= S!int(...);
> array ~= S!double(...);
> array ~= S!long(...);
> array ~= "I am a string!";
>
> And this is probably not what you want.
You can do this if you want to ensure that items stored in the
variant are of
a specific template struct/class.
import std.traits, std.variant;
struct TemplateStruct(alias template_)
{
private Varint v;
void opAssign(TemplateStruct!template_ other)
{
this.v = other.v;
}
void opAssing(T)(T t) if(isInstanceOf!(template_, T))
{
this.v = t;
}
T* peek(T) { return v.peek!T; }
auto visit(Handlers...) { return v.visit!handler; }
//More variant stuff here.
}
This should work: (untested)
TemplateStruct!(S)[] array;
array ~= S!int(...);
array ~= S!long(...);
array ~= S!double(...);
array ~= "I am a string!"; //This line should issue a compiler
error.
To complete TemplateStruct simply forward the remaing members of
the
variant. Or use something like proxy!T in std.typecons. Or use an
alias this v.
(I don't really recommend alias this it has all kinds of problems)
More information about the Digitalmars-d-learn
mailing list