@templated()
bearophile
bearophileHUGS at lycos.com
Tue Jan 11 14:22:51 PST 2011
(I am busy, I am late with some answers, I am sorry, I will catch up)
This paper is "Minimizing Dependencies within Generic Classes for Faster and Smaller Programs", by Dan Tsafrir, Bjarne Stroustrup and others:
http://www2.research.att.com/~bs/SCARY.pdf
The article shows problems of C++/D template bloat, and a way to avoid some of it. It talks a bit about D too, in two points. Near the end it shows an idea for C++-like languages, Figure 21, page 18:
template<typename X, typename Y, typename Z> struct C {
void f1() utilizes X,Z {
// only allowed to use X or Z, not Y
}
void f2() {
// for backward compatibility, this is
// equivalent to: void f2() utilizes X,Y,Z
}
class Inner_t utilizes Y {
// only allowed to use Y, not X nor Z
};
};
I have adapted it to a possible syntax for D:
struct C(X, Y, Z) {
// only allowed to use X or Z, not Y
@templated(X,Z) void f1() {
}
// for backward compatibility, this is
// equivalent to: @templated(X,Y,Z) void f2()
void f2() {
}
// only allowed to use Y, not X nor Z
@templated(Y) static class Inner {
}
}
The purpose of @templated() is to help the compiler avoid some template bloat. Here the class Inner is allowed to use just the Y template argument of C, this means that if you instantiate C in two ways like this:
C!(int, int, float)
C!(float, int, double)
The Y doesn't change, so the compiler instantiates the code of Inner only once. If you try to use X or Z in Inner it will not compile.
A sufficiently smart compiler is able to remove duplicated functions with no need of @templated(), in practice an annotation may help reduce compiler work or compilation time, to produce smaller code. It also helps document a bit of the semantics of the code, an enforced documentation.
Bye,
bearophile
More information about the Digitalmars-d
mailing list