1. はじめに
C++のテンプレートは、関数やクラスを汎用的に扱うための機能です。型を一般化することで、コードの再利用性を向上させることができます。
本記事では、C++のテンプレートの基本から実践的な使い方までを詳しく解説します。
2. 関数テンプレートとは?
通常の関数との違い
通常の関数では、異なる型に対して同じロジックを適用する場合、それぞれの型ごとに関数を定義する必要があります。
#include <bits/stdc++.h>
using namespace std;
// int型の二乗を計算する関数
int square_int(int x) {
return x * x;
}
// double型の二乗を計算する関数
double square_double(double x) {
return x * x;
}
int main() {
int a = 3;
double b = 1.2;
cout << square_int(a) << endl;
cout << square_double(b) << endl;
}
この方法では、型ごとに関数を定義しなければならず、冗長になってしまいます。
関数テンプレートの基本構文
テンプレートを使うことで、異なる型でも共通のロジックを持つ関数を一つにまとめることができます。
#include <bits/stdc++.h>
using namespace std;
// 関数テンプレート
template <typename T>
T square(T x) {
return x * x;
}
int main() {
int a = 3;
double b = 1.2;
cout << square<int>(a) << endl; // int版のsquare関数
cout << square<double>(b) << endl; // double版のsquare関数
}
関数テンプレートの使い方
関数テンプレートの呼び出し時には、<T>
の部分を指定することで特定の型を適用できます。
関数名<テンプレート引数>(引数1, 引数2, ...);
C++のコンパイラは型推論も行うため、明示的に <int>
などを指定しなくても動作する場合があります。
3. クラステンプレートとは?
クラステンプレートの基本構文
クラステンプレートを使うと、異なる型を扱う構造体やクラスを共通のテンプレートとして定義できます。
#include <bits/stdc++.h>
using namespace std;
// クラステンプレートの宣言
template <typename T>
struct Point {
T x;
T y;
void print() {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
// int型のPoint構造体
Point<int> p1 = {0, 1};
p1.print();
// double型のPoint構造体
Point<double> p2 = {2.3, 4.5};
p2.print();
}
クラステンプレートの使い方
構造体名<テンプレート引数>
クラステンプレートを使うことで、異なる型に対して同じロジックを適用することができます。
4. 定数のテンプレート
C++では、定数にもテンプレートを適用できます。
定数テンプレートの基本構文
template <typename T>
const T 定数名 = 値;
例:タプルの要素を交換する関数
以下のコードは、テンプレートを利用してタプルの特定の要素を交換する関数を実装しています。
#include <bits/stdc++.h>
using namespace std;
// タプルのINDEX1番目とINDEX2番目を交換する関数
template <int INDEX1, int INDEX2>
void tuple_swap(tuple<int, int, int> &x) {
swap(get<INDEX1>(x), get<INDEX2>(x));
}
int main() {
tuple<int, int, int> x = make_tuple(1, 2, 3);
tuple_swap<0, 2>(x); // 1番目と3番目を交換
cout << get<0>(x) << ", " << get<1>(x) << ", " << get<2>(x) << endl;
tuple_swap<0, 1>(x); // 1番目と2番目を交換
cout << get<0>(x) << ", " << get<1>(x) << ", " << get<2>(x) << endl;
}
5. まとめ
C++のテンプレートを活用することで、型に依存しない汎用的なコードを記述できるようになります。
本記事のポイント
テンプレートの概念を理解し、実際の開発に活かしてみてください!