Dispatching from receive to a function
Bob Cowdery
bob at bobcowdery.plus.com
Mon Sep 27 14:17:12 PDT 2010
Thanks for the suggestions. I'm still hankering after an elegant
solution to the receive rather than try to patch it up after the event.
The best I can come up with is pretty ugly (odd) at the front but looks
better at the back-end. Maybe someone can refine it a bit.
struct RATE{};
struct SRC_1{};
struct SRC_2{};
class OutputFrame{
void set_rate(RATE desc, int speed) {..}
void set_clock_src1(SRC_1 desc, string lo_ref){...}
void set_clock_src2(SRC_2 desc, string hi_ref) {...}
}
output_buffer = new OutputFrame();
while (true) {
receive(
(immutable (float) [] smpls) {
add_to_buffer(smpls);
output_data();
},
&output_buffer.set_rate,
&output_buffer.set_clock_src1,
&output_buffer.set_clock_src2,
);
}
On 27/09/2010 20:49, Juanjo Alvarez wrote:
> 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