-qtempinc を使用するには、アプリケーションを次のように構成する必要があります。
こうすると、次のような結果が得られます。
この例には、次のソース・ファイルが含まれています。
この例では、
このヘッダー・ファイルは、クラス 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
このファイルは、クラス 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); }
このヘッダー・ファイルには、add 関数のプロトタイプが含まれています。このプロトタイプは、stackadd.cpp および stackops.cpp で使用されます。
void add(Stack<int, 50>& s);
このファイルは、add 関数のインプリメンテーションを提供するものです。このインプリメンテーションは、メインプログラムから呼び出されます。
#include "stack.h" // (1) #include "stackops.h" // (2) void add(Stack<int, 50>& s) { int tot = s.pop() + s.pop(); s.push(tot); return; }
このファイルで、Stack オブジェクトが作成されます。
#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); }
コンパイラーは、個々のテンプレート・インプリメンテーション・ファイルに対応する TEMPINC ディレクトリーに、テンプレート・インスタンス化ファイルを作成します。コンパイルを行うたびに、コンパイラーはそのファイルに情報を追加することはできても、そのファイルから情報を除去することはありません。
プログラムを開発する際には、テンプレート関数参照を除去したり、プログラムを再編成したりして、テンプレート・インスタンス生成ファイルの内容が古くなることがあります。 TEMPINC 宛先を定期的に削除し、プログラムを再コンパイルしてください。
従来のアプリケーション開発環境では、異なるアプリケーション同士がソース・ファイルとコンパイル済みファイルを共用することができます。テンプレートを使用すると、ソース・ファイルは共用できますが、コンパイル済みファイルは共用できません。
-qtempinc を使用する場合は、次のことに注意してください。