Dispatching from receive to a function

Juanjo Alvarez juanjux at thatwebmailofgoogleproperty.com
Mon Sep 27 12:49:54 PDT 2010


On Mon, 27 Sep 2010 21:00:48 +0200, Johannes Pfau wrote:

> On 27.09.2010 20:46, Juanjo Alvarez wrote:
>> I'm new to the language so I don't know if this is horribly wrong on
>> some levels, but it works:
>> 
>> -----------------------------
>> 
>> import std.variant;
>> import std.stdio;
>> 
>> class C
>> {
>>     bool test(int i, char c) { writeln("Hello from test1"); return
>>     true; } void test2(string v) { writeln("Hello from test2, ", v); }
>> }
>> 
>> 
>> void main()
>> {
>>     auto c = new C;
>>     Variant[string] holder = ["test": Variant(&c.test), "test2":
>>     Variant
>> (&c.test2)];
>>     receiver(holder);
>> }
>> 
>> void receiver(Variant[string] message) {
>>     // If you get the Variant template instantiation delegate //
>>     signature wrong, it will
>>     // be detected at compile time!
>>     auto t = message["test"].get!(bool delegate(int, char)); auto t2 =
>>     message["test2"].get!(void delegate(string)); t(1, 'c');
>>     t2("foo");
>> }
>> --------------------------
>> 
>> Curiously if you create holder like this, it will give an
>> arrayoutofbound error at runtime, I don't know if that is a bug:
>> 
>> void main()
>> {
>>    auto c = new C;
>>    Variant[string] holder;
>>    holder["test"] = Variant(&c.test);
>>    holder["test2"] = Variant(&c.test2);
>> }
>> 
>> 
> I totally forgot about Variant!
> As far as I know that's exactly what variant is for and it's way better
> than my proposed hack. The example you posted is perfectly fine as well.
> I'm not sure what causes the arrayoutofbound error, the second example
> is correct as well.

Yep, variants are cool. You could even use an struct as value type of the 
associative array and store the variant in one member and the signature 
of the delegate, as string, in another member. The you could use a mixin 
in the receiver to extract the delegate without knowing the original 
signature.

All this is  wonderfully disturbing to me :)


More information about the Digitalmars-d-learn mailing list