C++ to D

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 11 10:59:58 PDT 2015


On 03/11/2015 07:33 AM, Dennis Ritchie wrote:

> How to rewrite this in D to the handler method for the input parameter
> was determined on average in O(1)?

D's associative arrays are hash tables.

The following program is as similar to the C++ one as possible:

import std.stdio;
import std.range;

class A
{
public:
     alias Func = void delegate(A, string);
     static const Func[string] handlers;

     static this()
     {
         handlers = [ "first" : (A a, string b) => a.foo1(b),
                      "second" : (A a, string b) => a.foo2(b),
                      "third" : (A a, string b) => a.foo3(b) ];
     }

     void foo(string s)
     {
         const handler = s in handlers;
         if (handler) {
             (*handler)(this, s);
         }

         m_buf ~= s ~ ' ';
     }

protected:
     void foo1(string s)
     {
         writeln(s);
     }

     void foo2(string s)
     {
         writeln(s.retro);
     }

     void foo3(string s)
     {
         writefln("%s, %s", s, m_buf);
     }

     string m_buf;
}

void main()
{
     auto a = new A();
     a.foo("first");
     a.foo("second");
     a.foo("third");
}

Ali



More information about the Digitalmars-d-learn mailing list