Understanding Templates: why can't anybody do it?
H. S. Teoh
hsteoh at quickfur.ath.cx
Sat Mar 17 15:23:47 PDT 2012
On Sat, Mar 17, 2012 at 10:15:26PM +0100, Simen Kjærås wrote:
> On Sat, 17 Mar 2012 21:56:14 +0100, novice2 <sorry at noem.ail> wrote:
>
> >How it come, that we build another abstartion level above strong
> >typed language?
> >Onece we builded high level language above assembler. Are we now
> >building another more high level? Will temlate will become another
> >language used as complete language? Will generic prigramming
> >become mainstream, like high level languages today?
>
> It seems to me that templates are mostly useful for libraries. In user
> code this flexibility is rarely as useful. It may however be that this
> very same argument was put forth when OO was introduced.
I disagree. I use templates all the time, in my own code. It's a great
way to factor out common code, so that you avoid code duplication (which
often also means bug duplication).
For example, I'm writing a grid-based game, where I have a Board class
that stores an array of tiles representing game pieces. For various
reasons (not relevant here), I decided I should store the tiles as a
linear array, and just overload opIndex() to provide "2D access":
class Board {
Tile[] tiles;
int width, height;
Tile opIndex(int x, int y) {
return tile[offsetOf(x,y)];
}
private int offsetOf(int x, int y)
in { assert(x>=0 && x<width && y>=0 && y<height); }
out(z) { assert(z>=0 && z<tiles.length); }
body {
return x + y*width;
}
}
Later on, after I've implemented a working game, I decide to make the AI
player a bit smarter. For that, I decided to have the AI precompute
optimal movement paths by assigning an integer to each tile, and then
scanning the board to find optimal paths based on the ints assigned to
each tile.
I *could* add an int to Tile and use that, but the problem is, they are
only used during the pre-game computation by the AI; the computed paths
are stored separately after this computation is done, so the integers
are not needed during the actual gameplay. So storing the ints in Tile
is a waste of space.
So what I really need is a Board that stores ints instead of Tiles. But
the current Board class is already bound to Tile's! What can I do?
Aha! I can make Board a template:
class Board(T) {
T[] tiles;
int width, height;
T opIndex(int x, int y) { ... }
...
}
Then for the actual game board, I'd have:
Board!Tile gameboard;
And for the AI's precomputed data, I'd have:
Board!int aidata;
After the AI has found the optimal paths, I can discard aidata and
continue using gameboard.
Situations like this arise quite often in my code. So I'd say that
templates are definitely not limited to library code. They are generally
applicable.
T
--
Famous last words: I *think* this will work...
More information about the Digitalmars-d
mailing list