[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: C++

From: Bas Wijnen
Subject: Re: C++
Date: Mon, 9 Nov 2009 14:45:48 +0100
User-agent: Mutt/1.5.18 (2008-05-17)

On Mon, Nov 09, 2009 at 10:56:29PM +1100, William Leslie wrote:
> [templates] really are compile-time code generation.

Yes, they must be because compiled code doesn't know about types.  So
the linker cannot choose the proper function depending on the type: it
doesn't know about types.  The reason languages like Python an
javascript can do this, is that they are interpreted languages, so that
compile-time is the same as run-time (Python-"compiling" is only

> This means that two compilation units that use minimum<int> will each
> have their own instance of it.

But there is a solution to that, which is implemented in C++: think make
each instance a weak symbol, which may be multiply defined.  If it is,
only one function is actually included at link time.

Also, you can include certain instantiations of the template in the
library.  If the compiler needs it, it will call the library function
instead of creating its own.

I think this may be what Antrik was referring to: you can explicitly
tell the compiler to instantiate the template for a certain type.  This
is only needed when building a library, where you want the instance
without using it.  When a template is used, the instance is
automatically created.

> It seems like it would be difficult to reason about how much
> duplication would occur in a largeish project.

Because of the two methods above, there is no code duplication at all.

> Worse, because you can't put them into a library and have template
> parameters resolved at link time, changes to templates require
> rebuilding all the code that uses them.  It's a very inconvenient way
> to achieve code reuse IMHO.

This is true, indeed (if the code that uses them instantiates the
template, and it usually does).  But there is no way to achieve this,
because a precompiled library is incapable of resolving types.  So it
doesn't get better than this.  If this is not good enough, then you'll
have to live without templates.  Appearantly you do, and I did as well,
but I'm very happy that I don't have to anymore. :-)

You do have a point about the error messages though.  It still shows
that C++ was originally just a C preprocessor.  Some errors can only be
understood if you know how the feature is implemented.


Attachment: signature.asc
Description: Digital signature

reply via email to

[Prev in Thread] Current Thread [Next in Thread]