Struct initialization, implicit conversions and delegates
Nicolas Silva
nical.silva at gmail.com
Mon Jan 16 11:54:58 PST 2012
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20120116/41386fd5/attachment.html>
More information about the Digitalmars-d-learn
mailing list