Structuring Your Program Using Templates

You can structure your program three ways using templates:

  1. the function template definition (both the .h and .c files) in all files that may reference the corresponding template functions.
  2. the function template declaration (the .h file only) in all files that may reference the corresponding template functions, but include the function definition (both the .h and .c files) in one file only.
  3. the declaration of the function templates in a header file and the definition in a source file that has the same name. When you include the header file in your source, the compiler automatically generates the template functions. Use the /Ft+ option to enable this method.

The following examples use two files to illustrate all three methods: stack.h and stackdef.h

To instantiate a stack of 50 ints, you would declare the following in each source file that requires it:

stack<int> intStack(50);

For method 1, each source file using the template should include both stack.h and stackdef.h.

For method 2, every source file should include stack.h, but only one of the files needs to include stackdef.h.

For method 3, every source file should include stack.h. The compiler automatically generates the template functions in the TEMPINC subdirectory that is created in the current directory. To use this method, copy stackdef.h to stack.c and use the /Ft+ option, which is the default .

Note: C++ objects with templates can now be linked as a separate step with the IBM C and C++ Compilers linker command.



Class Templates


Template Syntax
Function Templates
Differences between Class and Function Templates