D template specialization in different source file

Viewed 421

I recently asked this question about how to simulate type classes in D and suggested a way to do this using template specialization.

I discovered that D doesn´t recognize template specialization in a different source file. So I couldn´t just make a specialization in a file not included from the file where the generic function is defined. To illustrate, consider this example:

//template.d
import std.stdio;
template Generic(A) {
  void sayHello() {
    writefln("Generic");
  }
}

void testTemplate(A)() {
    Generic!A.sayHello();
}


//specialization.d
import std.stdio;
import Template;

template Generic(A:int) {
  void sayHello() {
      writefln("only for ints");
  }
}

void main() {
    testTemplate!int();
}

This code prints "generic" when I run it. So I´m asking whether there is some good workaround, so that the more specialized form can be used from the algorithm.

The workaround I used in the question about Type classes was to mixin the generic functions after importing all files with template specialization, but this is somewhat ugly and limited.

I heard c++1x will have extern templates, which will allow this. Does D have a similar feature?

2 Answers
Related