Proposal: Treat static assert in template as instantiation error

Christian Kamm kamm at incasoftware.de
Mon Aug 28 22:40:24 PDT 2006


On Mon, 28 Aug 2006 23:25:27 +0200, Kirk McDonald  
<kirklin.mcdonald at gmail.com> wrote:

> It has become a common idiom with D's templates to test a template  
> parameter against a series of static if/else static if statements, and  
> if none of them match, to set a static assert(false). For example:
>
> [temp_test2.d]
> import std.stdio;
>
> void func1(T) (T t) {
>      static if (is(T == int)) {
>          writefln(t + 1);
>      } else static if (is(T == char[])) {
>          writefln(t ~ "1");
>      } else static assert(false, "I don't know how to handle this!");
> }

What about

[temp_test3.d]
import std.stdio;

void func1(T : int) (T t) {
   writefln(t + 1);
}

void func1(T : char[]) (T t) {
   writefln(t ~ "1");
}

void func2(T) (T t) {
   func1!(typeof(T))(t); // line 12
}

void main() {
   func2("Hello".dup);
   func2(25.5); // line 17
}

Here the compiler output is
test.d(12): template instance func1!(double) does not match any template  
declaration
test.d(12): template instance 'func1!(double)' is not a variable
test.d(12): function expected before (), not func1!(double) of type int
test.d(17): template instance test.func2!(double) error instantiating

However, maybe I'm missing the point here, since there are probably things  
you can do with static if that won't work through specializations. Also,  
it could be redundant if you want to specialize for all numeric types for  
example. Finally, this circumvents the 'specialized parameters can't be  
implicitly deducted' rule, which likely has some ambiguity rationale.

Cheers,
Christian



More information about the Digitalmars-d mailing list