Templates - What's Up with the template keyword?
Steven Schveighoffer
schveiguy at gmail.com
Tue Apr 9 20:48:45 UTC 2019
On 4/9/19 4:31 PM, Ron Tarrant wrote:
> I'm still struggling to understand templates, but I'll keep at it.
When I first saw C++ templates, I thought "what the hell is this black
magic", and had no idea how they worked. In fact, this was back before
STL, and I recall it was a set of templates called "Rogue Wave". None of
us who were working on the project at the time understood them, so we
ripped them all out.
The thing that made it click for me is that a template is very akin to a
macro substitution -- where you just copy and paste the given parameter
wherever its substitute is found.
For example:
struct S(T)
{
T member;
}
S!int => put int wherever you see T.
So it's like you typed:
struct S
{
int member;
}
and that's what the compiler sees. All optimization, layout, etc. works
exactly like you typed that directly. But instead of creating one type
for every member type you need, you just write it once and "instantiate"
the template giving the type you want.
I will say, it's not EXACTLY the same as macro substitution -- there are
rules. But it's a good way to think about it. I actually am going to go
over this kind of thinking a bit in my talk this year at dconf.
-Steve
More information about the Digitalmars-d-learn
mailing list