The D programming language, part 2

Generic programming

We start with a simple example, the min function, that should work for all ordered types. First prototype

auto min(L,R)(L lhs, R rhs){
return rhs < lhs ? rhs : lhs;

But! now min(42,”hello”) will generate an error. Andrei adds that using just of type argument is not enough, since float and int (for instane) can be compared. So what it th right thing?

auto min(L,R)(L lhs, R rhs){
if(istypeof(rhs<lhs) == bool{
return rhs < lhs ? rhs : lhs;}

Only if there is a compare, we will execute it. More beautiful solution is to put the typeof part in a template on the typew L and R and use init (default values) instead of on the arguments. Now this can be used everywhere.

template ordered(L,R) {
enum= ordered = if(istypeof(L.init < R.init) == bool);

Embedded DSLs

To enable this, we need two D features: static and mixin.

By using static in D, a function is evaluated at compile time and turned into a constant that can be used at runtime. A large subset of D is available at compile-time, but no unsafe features and no IO. With the mixin command, you can do code injection. “not as glorious as AST manipulation, but darn effective” With those two commands, we can generate code and compile on the fly, for instance to create an embedded DSL.


This post was visited 67 times.