Struct initialization, implicit conversions and delegates

Nicolas Silva nical.silva at
Mon Jan 16 11:54:58 PST 2012


I have two syntactic "difficulties" when initializing structs:

Say I have a struct StringHash that represents the hash code of a string.

struct StringHash
    this( string str )

    void computeHash( string str )
        hash = 0;
            hash ^= c;
            hash *= 0x93;

    bool opEquals( ref const(StringHash) s )
        return hash == s.hash;

    bool opEquals( string s )
        return hash == StringHash(s).hash;

    uint hash;

I would like this structure to be as transparent as possible and be able to
write things like:

StringHash sh = "SomeString"; // ok

struct Foo
    StringHash name;

Foo foo = {
   name : "SomeString" //  Error: cannot implicitly convert expression
("SomeString") of type string to StringHash
   category : HString( "SomeString" ); // works, but looks less nice IMO.

It looks like I can't initialize fields of a struct with anonymous
functions or delegates (the error is not clear to me though), for example:

struct Element
   void delegate(void) onSomething;
   void delegate(void) onSomethingElse;

void main()
    auto callBack = delegate void(void) { stdout.writeln("callBack"); };

    Element e = {
        onSomething : callBack, // ok
        onSomethingElse : delegate void(void) {
stdout.writeln("anonymous"); } // errors (this is line 15, see below)

test.d(15): found ':' when expecting ';' following statement
test.d(16): found '}' when expecting ';' following statement
test.d(19): semicolon expected, not 'EOF'
test.d(19): found 'EOF' when expecting '}' following compound statement

Both of these little problems are not crucial, but they could bring some
very nice syntactic sugar on the API I am designing right now.
how should I fix it?
If the actual behaviors are desired i'd be interested to know the arguments
(well, i can imagine motivation for explicit conversion, but for the
delegate thing it's less clear to me).


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Digitalmars-d-learn mailing list