Template with template?

John Colvin john.loughran.colvin at gmail.com
Thu Mar 20 10:49:50 PDT 2014


On Thursday, 20 March 2014 at 16:40:50 UTC, Chris wrote:
> On Thursday, 20 March 2014 at 16:32:34 UTC, Vladimir Panteleev 
> wrote:
>> On Thursday, 20 March 2014 at 16:28:46 UTC, Chris wrote:
>>> How can I instantiate Person with Trait, i.e. a template with 
>>> a template?
>>>
>>> struct Trait(T0, T1) {
>>> T0 name;
>>> T1 value;
>>> T1[T0] map;
>>>
>>> this(T0 name, T1 value) {
>>>   this.name = name;
>>>   this.value = value;
>>>   map[name] = value;
>>> }
>>> }
>>>
>>> class Person(T) {
>>> T traits[];
>>>
>>> void addTrait(T trait) {
>>>   traits ~= trait;
>>> }
>>> }
>>>
>>>
>>> void main()
>>> {
>>> auto trait1 = Trait!(string, string)("Name", "John");
>>> auto trait2 = Trait!(string, int)("Age", 42);
>>> writefln(%s", trait1.map);
>>> writefln(%s", trait2.map);
>>> // above code compiles and works
>>> }
>>
>> Person!(Trait!(string, string)) person;
>>
>> -- or --
>>
>> alias MyTrait = Trait!(string, string);
>> Person!MyTrait person;
>>
>> Note that this approach won't let you have traits with 
>> different parameters within the same Person type.
>
> Yep, I've already tried this (sorry I should've mentioned it!). 
> But I don't want this restriction.

Arrays are homogeneous. All the elements must be of the same 
type. Different instantiations of templates are different types.

You could use an array of std.variant.Variant


More information about the Digitalmars-d-learn mailing list