TITLE: Simple questions about templates? PROBLEM: an121669@anon.penet.fi Are templates expanded at compile-time or run-time? In the second edition of "The C++ Programming Language", Stroustrup strongly implies the former: Use of a template does not imply any run-time mecahnisms beyond what is used for an equivalent "hand-written class". (section 8.2) A header file may contain ... templates. (section 4.3) My biggest question really is "Must template function definitions be in header files, to be included by each user of the template, or can they be separately compiled?" Also, if templates are expanded at compile-time, does that mean that you can't distribute a template without giving away its implementation? RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 15 Sept 94 If templates were instantiated at run-time, the running program would have to halt on finding a missing function or class, invoke the compiler and linker, then continue. This seems an unlikely implementation except possibly for a C++ interpreter. You can expect templates to be expanded prior to run-time. Mechanisms vary considerably among C++ implementations, but consider this: If you supply a header "foo.h" containing template int foo(const T&); but do not supply the implementation of the foo template function, what would happen when a user writes #include "foo.h" class MyClass { ... }; MyClass m; int i = foo(m); How could the compiler generate a foo taking a MyClass if the template source code is not available? How could you as a supplier provide a precompiled foo(const MyClass&) if you had never heard of a MyClass? Some implementations require that template definition files be presented to the compiler along with the declaration files. Some don't. You can provide precompiled functions for common types such as int foo(const int&); int foo(const double&); int foo(const char*&); ... etc which will reduce the need to instantiate templates in user code. If you want to keep the implementation code secret, I don't see a way to allow "foo(const MyClass&)". [ Someone commented that the RogueWave Tools.h++ contains templates but they distribute an encrypted form of the template source code that only the compiler can read. -adc ]