Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

D Practice Problems: Classes, Templates and Metaprogramming

Twelve graded D exercises on classes, templates, mixins, compile-time code, concurrency and memory, with hints, D solution sketches and runnable C stand-in solutions.

Practice is how the earlier chapters stick. This lesson has twelve exercises on classes and templates, mixins and compile-time code, concurrency and memory and tooling. Try each on paper or in your own D compiler first; the hint is one click away in your head, and the stand-ins below let you check the ideas on this site.

D code is read-only on this site. Two exercises have runnable C solutions that exercise the same logic.

Warm-up

1. Shapes. Write an abstract class Shape with area() and a describe() that prints the name and area. Add Circle, Rect and Square (make Square extend Rect). Put them in an array and print the total area. Hint: the loop sees only Shape.

2. Generic min and max. Write minmax(T)(T[] a) returning a struct with min and max. Constrain T so it only accepts types with <. Hint: if (is(typeof(T.init < T.init))).

3. Stack with contracts. Create struct Stack(T) with push, pop and peek. Use in (!empty) on pop and peek, and write three unittest blocks.

Intermediate

4. Compile-time table. Build an immutable ubyte[256] table of the number of set bits per byte, using a function evaluated at compile time. Add static assert(table[255] == 8).

5. Property mixin. Write mixin template Property(T, string name) that generates a private field plus getter and setter. Use it on a Config struct with three properties.

6. Struct dumper. Write dump(T)(T value) that prints every field name and value using __traits(allMembers, T) and static if to skip methods.

7. Interface fat pointer. Define interface Logger with log(string). Implement ConsoleLogger and BufferLogger (stores lines). Write a function that takes a Logger and works with both. Then, in C, implement the same design with a struct of function pointers.

Advanced

8. Parallel word count. Given an array of strings, count the words in each in parallel and add the counts with taskPool.reduce. Explain why a shared counter would be wrong.

9. Worker with messages. A worker thread receives int jobs and replies with the sum of divisors of each. It stops on a bool message. Handle OwnerTerminated.

10. GC-free buffer. Write a @nogc struct FixedBuf(size_t N) with append(ubyte) that returns false when full. Add static assert(N > 0).

11. Scope guards. A function opens a resource, takes a lock and writes a file. Use scope(exit) and scope(failure) so a failure at any step releases exactly what was acquired and logs once.

12. C callback. Declare qsort in D with extern (C), sort an int[] descending with a comparator, and explain why the comparator must not be a delegate.

Worked solutions

Solution sketch for 1

D
abstract class Shape
{
    abstract double area() const;
    string name() const { return typeid(this).name; }
    void describe() const { writefln("%s: %.2f", name, area); }
}

class Rect : Shape
{
    double w, h;
    this(double w, double h) { this.w = w; this.h = h; }
    override double area() const { return w * h; }
}

class Square : Rect
{
    this(double s) { super(s, s); }
}

Square inherits area() unchanged, because a square is just a rectangle with equal sides. To check the totals, the C stand-in below uses a table of function pointers, the same dispatch D performs.

C Stand-in solution for 1: total area through a vtable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Solution sketch for 4

D
ubyte[256] makeBits()
{
    ubyte[256] t;
    foreach (i; 0 .. 256)
    {
        int v = i, n = 0;
        while (v) { n += v & 1; v >>= 1; }
        t[i] = cast(ubyte) n;
    }
    return t;
}

immutable bitsSet = makeBits();
static assert(bitsSet[255] == 8 && bitsSet[0] == 0 && bitsSet[5] == 2);

The immutable module-level initializer forces compile-time evaluation, so the static assert also runs then. The C program computes the same table and checks it at run time.

C Stand-in solution for 4: bits-set table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Solution sketch for 8

D
import std.algorithm : splitter;
import std.array : array;

size_t words(string s) { return s.splitter(' ').array.length; }

size_t totalWords(string[] lines)
{
    return taskPool.reduce!"a + b"(0UL, lines.map!(words));
}

(map needs import std.algorithm : map;.) A shared size_t count; foreach (l; parallel(lines)) count += words(l); loses updates: use reduce or core.atomic.

Hints for the rest

  • 2: return Tuple!(T, "min", T, "max") and start from a[0]; contract in (a.length > 0).
  • 3: store items in T[]; pop needs in (items.length > 0).
  • 5: build the member strings with mixin(...) as in the mixin templates lesson.
  • 6: __traits(getMember, value, name) and is(typeof(...) == function).
  • 9: receive((int n) { ... }, (bool stop) { ... }, (OwnerTerminated) { ... }).
  • 10: T[N] data; size_t len; and no new; mark the methods @nogc nothrow.
  • 11: scope(failure) once at the top for the log; scope(exit) immediately after each acquisition.
  • 12: the comparator is extern (C) int cmp(const(void)*, const(void)*); a delegate carries a hidden context pointer that C cannot supply.

Where next

You have now covered the object system, generic and compile-time programming, concurrency, memory control and tooling. Good next steps:

  1. Read the standard library's source for std.algorithm: it is the best example of templates, ranges and constraints.
  2. Build a command-line tool with std.getopt, std.json and dub.
  3. Try a web service with vibe.d or a game with raylib-d.
  4. Return to the track overview to revisit any chapter.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why does a shared counter updated inside parallel foreach give wrong results?

    Use reduce, atomics or a lock.
  2. 2. Why must a C callback be an extern (C) function and not a delegate?

    C expects a plain function pointer; use a void* user argument for context.
  3. 3. Which keyword forces makeBits() to run at compile time here?

    A module-level immutable needs a compile-time initializer, so the compiler evaluates the call.

Summary

  • Twelve exercises cover classes, templates, mixins, CTFE, concurrency, memory and C interop.
  • Solutions follow the same patterns as the lessons: virtual dispatch, constraints, compile-time tables, reduce instead of shared counters.
  • Keep practising with the standard library source and small real tools.

Next: Back to the D track