How to do Generic Programming in D?
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Tue Feb 22 14:35:14 PST 2011
On 2/22/11 1:04 PM, Nick wrote:
> Coming from Andrei's work in C++ "Modern C++ Programming" I wonder how
> to implement many of those patterns in D?
>
> In C++ I would work with type lists and use lots of multiple inheritance
> and templates to get the magic I need.
>
> D lacks MI, classes and delegates seem heavy (allocated on heap, with
> one extra pointer and new for each delegate) and has instead template
> mixins which do not create types and string mixing which create...
> anything.
>
> So I am a bit lost.
>
> I guess I am looking for some code&examples to read to "get" GP in D. A
> bit like "Modern C++ Programming".
>
> Of course, the basic question being: is D2 sufficient to support
> everything that is possible in C++?
>
> Thanks!
Welcome to the group.
Using D for the kind of generic designs featured in MC++D may be a bit
disconcerting because a lot of the C++ implementation is forced to use
unintuitive mechanisms to get things done. The expectation is that the
same mechanisms need to be used for the D implementation, too, which
shouldn't be the case. In fact accomplishing any of MC++D's tasks is
considerably easier in D.
For example, indeed in C++ a policy-based design would need to use
multiple inheritance. But this is not motivated by a need for multiple
subtyping - MI is just the best proxy C++ has for injecting
parameterized implementation. In D for that goal you'd use mixin
templates, or for ultimate flexibility string mixins. If you do need
multiple subtyping, you'd use classes in conjunction with e.g.
parameterized interfaces and/or "alias this".
Typelists are an elaborate C++ construct that is essentially built in
into D.
For the Command pattern, delegates would be a great start. Added value
for e.g. currying and binding is trivial to implement, to the extent
that we decided to deprecate a dedicated module (std.bind).
There would be more to say. One way or another, policy-based design is
difficult and often unintuitive. Therefore, it requires mastery of both
the design topic at hand and of the implementation language. I think
trying to get a solid PBD component off the ground as a D beginner would
be pushing it. Nevertheless, it may be worth a try. I suggest starting
with a simple, well-defined component such as Object Factory.
Andrei
More information about the Digitalmars-d
mailing list