On 2015-03-11 at 17:42, Dennis Ritchie wrote:
On Wednesday, 11 March 2015 at 16:08:22 UTC, Kagamin wrote:
A hash table? See http://dlang.org/hash-map.html

That is, the input is a string and, depending on what word it contains, is 
called one of the three methods of the class that this line handles. And this 
happens in average constant time (for hash). An associative array where the key 
is a string and value is a function.

Yeah, lookup in D's associative arrays is generally O(1).
Here's the D version of your C++ code. A bit modified, to be more practical,
i.e. you can register hooks yourself and not have them hard-coded into the 
class.



import std.stdio, std.range;

class A
{
    alias Hook = void function(ref A, string);
    string m_buf;
    Hook[string] handlers;
    void foo(string s) {
        if (auto p = s in handlers)
            (*p)(this, s);
        m_buf ~= s ~ " ";
    }
    void register(string name, Hook hook) {
        handlers[name] = hook;
    }
}

void foo1(ref A a, string s) { writeln(s); }
void foo2(ref A a, string s) { writeln(s.retro); }
void foo3(ref A a, string s) { writeln(s, ", ", a.m_buf); }

void main() {
    A a = new A;
    a.register("first", &foo1);
    a.register("second", &foo2);
    a.register("third", &foo3);
    a.foo("first");
    a.foo("second");
    a.foo("third");
}

Reply via email to