How to do Generic Programming in D?

Adam D. Ruppe destructionator at gmail.com
Tue Feb 22 15:32:29 PST 2011


Nick wrote:
> Of course, the basic question being: is D2 sufficient to support
> everything that is possible in C++?

So far, everything I've tried has not only been possible, but quite
a bit easier.

Last weekend, I had to go back to C++ to do some quick work. I wanted
to port a boxer function over. In D, I used a variadic template,
foreach, and static if to it off.

The code was about 100 lines long and either worked for all types
or failed meaningfully.


C++ couldn't take that approach. I figured I could get closer
if I used some C++0x features, and since this project only had
to work in environments I control, I enabled them and went to
town.

C++0x felt like a crippled, inelegant D. Yes, it has variadic
templates, but without foreach, I had to use recursion to go
over them. Without static if and template constraints, it was
a mess of overloaded functions and what felt like horrible
abuses of SFINAE.

A simple looped assignment, 4 lines in D, became about 60 lines of
bizarre overloads and recursion, and still didn't handle all
the types quite as elegantly as D.

When it was all said and done, the 100 lines of D became about
250 lines of C++0x. (There's other features that are pretty equal
so it wasn't all so lopsided).

Then, the real ugliness came in. In D, you can do compile time
reflection. Want to automatically implement an interface with
the boxer function? Another simple foreach loop with static ifs
to round it off.

I couldn't figure it out in C++. It was probably possible, but it
was too hard for my simpleton brain to handle. I ended up writing
a helper code generator for it.

(btw, on code generators, if you
write one in D, you can probably call it at compile time and
generate the code all at once... no need for extra steps in your
build process! See string mixins and CTFE for how. Short answer:
write the code generator as a function returning a string with
the code. Then do mixin(myCodeGenFunction()); It'll probably
work!)


That's the big difference between C++ and D. C++ makes it possible.
D makes it accessible.


More information about the Digitalmars-d mailing list