Dispatching from receive to a function

Johannes Pfau spam at example.com
Mon Sep 27 12:00:48 PDT 2010


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.

-- 
Johannes Pfau


More information about the Digitalmars-d-learn mailing list