www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Struct initialization, implicit conversions and delegates

reply Nicolas Silva <nical.silva gmail.com> writes:
Hi,

I have two syntactic "difficulties" when initializing structs:

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

struct StringHash
{
    this( string str )
    {
        computeHash(str);
    }

    void computeHash( string str )
    {
        hash = 0;
        foreach(c;str)
        {
            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.
};


2)
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).

Thanks,

Nicolas
Jan 16 2012
parent Trass3r <un known.com> writes:
 StringHash sh = "SomeString"; // ok

That's the only thing that works. An implicit tag for constructors to allow all implicit conversions would really be helpful. In general we need finer control of implicit conversions. Just have a look at ProxyOf: https://github.com/D-Programming-Language/phobos/pull/300/files#L0R2670 That's madness, all of that code just for getting alias this without implicit conversion to the original type.
Jan 16 2012