Proposal: Treat static assert in template as instantiation error
Kirk McDonald
kirklin.mcdonald at gmail.com
Mon Aug 28 14:25:27 PDT 2006
Currently, in dmd, if there is an error instantiating a template, the
compiler will quite helpfully print out a traceback to the original
point of instantiation:
[temp_test.d]
import std.stdio;
void func1(T) (T t) {
writefln(t + 1); // Line 4
}
void func2(T) (T t) {
func1(t); // Line 8
}
void main() {
func2("Hello".dup); // Line 12
}
$ dmd temp_test
temp_test.d(4): incompatible types for ((t) + (1)): 'char[]' and 'int'
temp_test.d(8): template instance temp_test.func1!(char[]) error
instantiating
temp_test.d(12): template instance temp_test.func2!(char[]) error
instantiating
It is then pretty clear what the problem is. (You can't pass a char[] to
func2.)
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!");
}
void func2(T) (T t) {
func1(t);
}
void main() {
func2("Hello".dup);
func2(25.5);
}
$ dmd temp_test2
temp_test2.d(8): static assert (0) is false, "I don't know how to
handle this!"
By throwing a static assert, the compiler aborts compilation
immediately, and the traceback information is lost. It is no longer
obvious where the template was originally instantiated from.
I propose that if a static assert is thrown from within a template, that
it be treated as a failed template instantiation. This would (the hope
is) result in the instantiation traceback being printed out. It would
allow coders to explicitly cause their templates to fail in a way that
is informative: Users would get both the message in the static assert as
well as the traceback information. I am sure this would be a great boon
to anyone writing or using template code.
--
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org
More information about the Digitalmars-d
mailing list