To use -qtempinc, you must structure your application as follows:
This produces the following results:
This example includes the following source files:
In this example:
This header file defines the class template for the class Stack.
#ifndef STACK_H #define STACK_H template <class Item, int size> class Stack { public: void push(Item item); // Push operator Item pop(); // Pop operator int isEmpty(){ return (top==0); // Returns true if empty, otherwise false } Stack() { top = 0; } // Constructor defined inline private: Item stack[size]; // The stack of items int top; // Index to top of stack }; #ifndef __TEMPINC__ // (3) #include "stack.c" // (3) #endif // (3) #endif
This file provides the implementation of the class template for the class Stack.
template <class Item, int size> void Stack<Item,size>::push(Item item) { if (top >= size) throw size; stack[top++] = item; } template <class Item, int size> Item Stack<Item,size>::pop() { if (top <= 0) throw size; Item item = stack[--top]; return(item); }
This header file contains the prototype for the add function, which is used in both stackadd.cpp and stackops.cpp.
void add(Stack<int, 50>& s);
This file provides the implementation of the add function, which is called from the main program.
#include "stack.h" // (1) #include "stackops.h" // (2) void add(Stack<int, 50>& s) { int tot = s.pop() + s.pop(); s.push(tot); return; }
This file creates a Stack object.
#include <iostream.h> #include "stack.h" // (1) #include "stackops.h" // (2) main() { Stack<int, 50> s; // create a stack of ints int left=10, right=20; int sum; s.push(left); // push 10 on the stack s.push(right); // push 20 on the stack add(s); // pop the 2 numbers off the stack // and push the sum onto the stack sum = s.pop(); // pop the sum off the stack cout << "The sum of: " << left << " and: " << right << " is: " << sum << endl; return(0); }
The compiler builds a template instantiation file in the TEMPINC directory corresponding to each template implementation file. With each compilation, the compiler can add information to the file but it never removes information from the file.
As you develop your program, you might remove template function references or reorganize your program so that the template instantiation files become obsolete. You can periodically delete the TEMPINC destination and recompile your program.
In a traditional application development environment, different applications can share both source files and compiled files. When you use templates, applications can share source files but cannot share compiled files.
If you use -qtempinc: