Reading — step 1 of 5
Learn
D's templates are like C++ but cleaner. Compile-time generics with constraints.
Function templates
T max(T)(T a, T b) {
return a > b ? a : b;
}
int x = max(3, 4); // T = int
double y = max(3.14, 2.71); // T = double
string s = max("abc", "xyz"); // T = string
The (T) after the function name is the template parameter list. Type inference fills it in.
Struct templates
struct Pair(A, B) {
A first;
B second;
}
auto p = Pair!(int, string)(1, "one");
auto q = Pair!(double, double)(3.14, 2.71);
Constraints
Limit which types are valid:
T add(T)(T a, T b) if (is(T : int) || is(T : double)) {
return a + b;
}
// add("hi", "there"); // compile error: violates constraint
This is D's equivalent of C++ concepts (which were added decades later).
Compile-time evaluation (CTFE)
long factorial(long n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
enum fact10 = factorial(10); // computed at compile time
Any pure function whose inputs are known at compile time can run at compile time.
Type inspection
import std.traits;
static if (is(T == int)) {
// ...
}
static if (isFloatingPoint!T) {
// ...
}
std.traits has isIntegral, isFloatingPoint, isArray, isAssociativeArray, etc.
Variadic templates
void printAll(T...)(T args) {
foreach (a; args) {
writeln(a);
}
}
printAll(1, "hello", 3.14);
The T... is a parameter pack. args is a variadic.
Why D templates win
- Faster compile times than C++
- Better error messages
static if,__traits, mixin templates — meta-programming actually pleasant- Compile-time function evaluation
D templates are arguably the highlight of the language. Many libraries (like Mir for numerical code) lean heavily on them for zero-cost abstractions.
Mixin templates (extra power)
mixin template Greeter(string name) {
string greet() { return "Hello, " ~ name; }
}
struct Person {
mixin Greeter!"Ada";
}
auto p = Person();
writeln(p.greet); // Hello, Ada
Mixin generates code at compile time. Used for visitor patterns, ORM column declarations, etc.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…