Parameterized Structs

Ali Çehreli acehreli at yahoo.com
Wed Mar 2 22:43:24 PST 2011


On 03/02/2011 08:56 PM, Peter Lundgren wrote:
> Where can I go to learn about parameterized structs? I can't seem to find any
> literature on the subject. In particular, what are you allowed to use as a
> parameter? I would like to define a struct like so:
>
> struct MyStruct(T, T[] a) {
>      ...
> }
>
> but I receive the following error:
>
> Error: arithmetic/string type expected for value-parameter, not T[]
>
> Are arrays not allowed?

Are you trying to parametrize by the type of the container or just 
trying to use an array of a specified type? (As opposed to say, a linked 
list of the specified type?)

If the former, it's simple. And the simplest thing is to just use an 
array in the implementation:

struct S(T)
{
     T[] a;

     void foo(T element)
     {
         /* Just use like an array */
         a ~= element;
         a[0] = element;
     }
}

void main()
{
     auto s = S!double();
     s.foo(1.5);
}

If you want to use a different container of the specified T, then a 
second template parameter can be used. This one uses an array as the 
default one:

class SomeContainer
{}

struct S(T, Cont = T[])
{
     Cont a;

     void foo(T element)
     {
         /* This time the use must match the allowed container types */
     }
}

void main()
{
     auto s = S!(double, SomeContainer)();
     s.foo(1.5);
}

I would recommend pulling information out ;) of this page:

   http://digitalmars.com/d/2.0/template.html

"Template Alias Parameters" is very different after C++ and can be very 
powerful:

   http://digitalmars.com/d/2.0/template.html#TemplateAliasParameter

Ali


More information about the Digitalmars-d-learn mailing list