Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

c++ - Are all template instantiations created at compile time?

After learning about variadic function templates that use recursion, I am wondering:

Are all template instantiations that can possibly be needed during the program's execution created at compile time? Is there such thing as instantiation on-the-fly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Templates are instantiated in the process of converting each translated translation unit into an instantiation unit.

A translation unit is essentially a source file.

A translated translation unit (try to say that three times fast) is the output from compilation without templates instantiated.

An instantiation unit is essentially the translated translation unit with templates instantiated.

Whether the instantiation occurs at "compile time" depends on the architecture of the implementation.

In a traditional "compile to objects and link the objects" architecture (which most developers working under windows or linux will be familiar with) the generation of translated translation units and generation of instantiation units are both phases (possibly combined phases) of the compiler. So, in this model, instantiation is a compile time activity.

However, there are implementations that use a "smart linker", and the compiler outputs translated translation units, with some auxiliary information that describes what template instantiations are needed by each translated translation unit. The process of converting those into an instantiation unit is then handled by the linker. With such implementations, template instantation is therefore a link-time activity rather than a compile time activity. The intent of this build model is that it provides opportunities for link-time optimisation (and the link-time template instantiation is more a side-effect than a goal).

The first implementation with a smart linker I encountered was available as an additional-cost option from Sun Microsystems on SunOS and later Solaris (those operating systems shipped by default with a toolchain that included a more typical dumb linker). I've encountered a couple of other such toolchains since, but can't recall their vendors offhand.

I'm not aware of any implementations where template instantiation occurs at run time. Conceivably, however, a C++ interpreter might work this way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...