C++ テンプレート
テンプレートはジェネリックプログラミングの基礎です。ジェネリックプログラミングとは、特定の型に依存しない方法でコードを記述することです。
テンプレートは、ジェネリッククラスやジェネリック関数を作成するための設計図または公式です。ライブラリコンテナ、例えばイテレータやアルゴリズムは、ジェネリックプログラミングの例であり、すべてテンプレートの概念を使用しています。
各コンテナには単一の定義があり、例えばベクターさまざまな型のベクターを定義できます。例えばvector <int> 或 vector <string>。
テンプレートを使用して関数やクラスを定義できます。次に、その使い方を見ていきましょう。
関数テンプレート
テンプレート関数定義の一般的な形式は次のとおりです。
template <typename type> ret-type func-name(parameter list)
{
// 関数の本体
}
ここで、type は関数が使用するデータ型のプレースホルダ名です。この名前は関数定義内で使用できます。
以下は、2つの数値の最大値を返す関数テンプレートの例です。
例
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}
上記のコードをコンパイルして実行すると、次の結果が得られます。
Max(i, j): 39 Max(f1, f2): 20.7 Max(s1, s2): World
クラステンプレート
関数テンプレートを定義するのと同様に、クラステンプレートも定義できます。ジェネリッククラス宣言の一般的な形式は次のとおりです。
template <class type> class class-name {
.
.
.
}
ここで、typeはプレースホルダ型名であり、クラスがインスタンス化されるときに指定できます。カンマ区切りのリストを使用して、複数のジェネリックデータ型を定義できます。
以下の例では、クラス Stack<> を定義し、要素をプッシュおよびポップするジェネリックメソッドを実装しています。
例
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class Stack {
private:
vector<T> elems; // 要素
public:
void push(T const&); // プッシュ
void pop(); // ポップ
T top() const; // スタックのトップ要素を返す
bool empty() const{ // 空なら true を返す
return elems.empty();
}
};
template <class T>
void Stack<T>::push (T const& elem)
{
// 渡された要素のコピーを追加
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop ()
{
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
// 最後の要素を削除
elems.pop_back();
}
template <class T>
T Stack<T>::top () const
{
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// 最後の要素のコピーを返す
return elems.back();
}
int main()
{
try {
Stack<int> intStack; // int 型のスタック
Stack<string> stringStack; // string 型のスタック
// int 型のスタックを操作
intStack.push(7);
cout << intStack.top() <<endl;
// string 型のスタックを操作
stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
}
catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
上記のコードをコンパイルして実行すると、次の結果が得られます。
7 hello Exception: Stack<>::pop(): empty stackその他の拡張