テンプレート
テンプレートとは、構造体や関数の型を一般化するための仕組み
関数テンプレートは処理の内容のひな型を作って、それを異なるデータ型に当てはめる
関数テンプレートの構文
template <typename テンプレート引数>
返り値の型 関数名(引数の型 引数名...){
// 処理内容
}
サンプルプログラム
#include <iostream>
using namespace std;
template <typename T>
T square(T x){
return x * x;
}
int main() {
cout << square(3) << endl;
cout << square(1.5) << endl;
return 0;
}
9
2.25
クラステンプレート
クラステンプレートとは、メンバ変数の型を一般化して作成するクラスのこと
クラステンプレートの構文
template <typename テンプレート引数>
class クラス名{
// クラスの内容
}
サンプルプログラム
#include <iostream>
using namespace std;
template <typename T>
class Point {
public:
T x;
T y;
Point(T arg1, T arg2){
x = arg1;
y = arg2;
}
void print() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point<int> point1(1,2);
Point<double> point2(1.2,3.4);
point1.print();
point2.print();
return 0;
}
(1, 2)
(1.2, 3.4)