C++ to D

Dennis Ritchie via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 11 07:33:02 PDT 2015


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

#include <string>
#include <iostream>
#include <functional>
#include <unordered_map>

class A
{
public:
     void foo(const std::string &s);

protected:
     void foo1(const std::string &s);
     void foo2(const std::string &s);
     void foo3(const std::string &s);

     std::string m_buf;
};

int main()
{
     A a;
     a.foo("first");
     a.foo("second");
     a.foo("third");
}

void A::foo(const std::string &s)
{
     using func = std::function < void(A &, const std::string &) >;
     static const std::unordered_map<std::string, func> handlers =
     {
         { "first",  std::mem_fn(&A::foo1) },
         { "second", std::mem_fn(&A::foo2) },
         { "third",  std::mem_fn(&A::foo3) }
     };

     const auto cit = handlers.find(s);
     if (cit != handlers.cend())
         cit->second(*this, s);

     m_buf += s + ' ';
}

void A::foo1(const std::string &s)
{
     std::cout << s << std::endl;    // prints first
}

void A::foo2(const std::string &s)
{
     std::cout << std::string(s.rbegin(), s.rend()) << std::endl;  
   // prints dnoces
}

void A::foo3(const std::string &s)
{
     std::cout << s << ", " << m_buf << std::endl;    // prints 
third, first second
}


More information about the Digitalmars-d-learn mailing list