Parameterized Structs

spir denis.spir at gmail.com
Thu Mar 3 07:31:05 PST 2011


On 03/03/2011 05:56 AM, 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?

Finally managed to do it, I guess :-)

============================
bool[E] set (E : E[]) (E[] elements) {
     bool[E] set;
     foreach (element ; elements)
         set[element] = true;
     return set;
}

struct String (C : C[], alias characters) {
     alias typeof(characters) S;
//~     alias ElementType!S C;	// BUG! returns dchar
     bool[C] klass = null;
     private C[] s;

     this (S s) {
         this.klass = set!S(characters);
         this.def(s);
     }
     void def (S s = null) {
         if (s.length == 0) {
             this.s = s;
             return;
         }
         foreach (ch ; s) {
             if (ch !in this.klass) {
                 auto message = format(
                     "'%s' not in allowed class of characters"
                     , ch);
                 throw new Exception(message);
             }
         }
         this.s = s;
     }

     string toString () {
         return format("String!(%s,\"%s\")(\"%s\")",
             S.stringof, characters, this.s);
     }
}

unittest {
     auto s = String!(string, "abcde")("");
     writeln(s);
     s.def("eca");
     writeln(s);
     s = String!(string, "abcde")("ace");
     writeln(s);
     s = String!(string, "abcde")("fgh");    // --> error
     writeln(s);
}
============================

Some notes:

* set is here to speed up character lookup among allowed klass (else, O(N) in 
array).

* C: C[] in struct template is redondant, since C[] is typeof(characters). It 
is only needed to declare the set 'klass', because of a bug: ElementType!string 
returns dchar!!! Thus, it is would not be possible, I guess, to declare klass's 
type in the struct definition.

* You must pass an init string (even if "") to call this() and construct klass. 
Because of another bug: there cannot be parameter-less constructors for 
structs. Also, set cannot be defined on toplevel of the struct def
     auto klass = set!S(characters);
because it's not a constant according to dmd. (It is, in fact). Thus, I guess 
we must construct it inside this().

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list