www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - My Bit on Templates

I realize that the C++ template engine is very, very powerful, basically a 
functional language as some have pointed out here.  I got about half way 
through andrescu's (spelling?) book when I realized... I don't need this 
mental masturbation.  I mean really, people are just going to be put off by 
having to work two weeks to understand what is behind a few ultimately 
ordinary features.  (Most programmers are on deadlines.)

As C++ stands, if you use templates you pretty much need to give any app 
coder your library code, which seems non-modular to me.  And in some cases, 
you have to tell the compiler to instantiate certain templates to get things 
to work.  As I understand it, this is the repurcussion of the flexibility of 

But on the other hand, here is my thought on a dramatically simpler template 
engine.  Suppose it was only powerful enough to do "containers" basically:


In other words, the main purpose is for type safe conglomerates.  Probably 
90% of the use of templates would still be covered and the other 10% 
probably doesn't get used by most people anyway.  The good news would be 
that these could be compiled into a new (AFAIK) type of binary.  It's been a 
while, but quickly a PIC object library has functions and references which 
can't be resolved until load time.  Then the loader puts the binary code 
into the same process space as the main app.  Once the beginnings of 
functions and literals are known, the references are resolved.

Well "template libraries" could also compile but the sizes of things would 
remain unresolved.  As an example, imagine a link lists of T's for some T. 
When this code is linked and used as an int and also a float, the size of 
the actual values are now known for T.  You can load two copies of the 
linked list into the apps address space with different resolutions for the 
size param.

I think this would be pretty cool.  Template libraries would come in ".tobj" 
format and quickly load in.  Compilers wouldn't have to give those asinine 
error comments for templates within templates within..

Another point, you could check at compile time that code is reasonable by 
limiting the scope of T.  In C++

    template <class T> void Dock( T* t )
        if ( T->IsUndocked() )  // how do we know t will be a boat?

    int i;
    Dock( i );

Compile didn't catch this when creating Dock(), only when calling it.  This 
code was silly.  If it were only going to work on boats, you didn't need a 
template.  You only needed a superclass function:

    void Dock( Boat* B );
Feb 18 2005