C++模板template使用

  1. 模板和函数template <typename x>
  2. 多个参数模板template <typename x, typename y>
  3. 结构体和模板
  4. 常数模版template <int x>

模板和函数template <typename x>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

// xの二乗を返す (関数テンプレート版)
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関数の呼び出し
cout << square(a) << endl;
// テンプレート引数の省略
}

多个参数模板template <typename x, typename y>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

// xの二乗を返す (関数テンプレート版)
template <typename T1, typename T2>
void print(T1 x, T2 y) {
cout << "typeof(x):" << typeid(x).name() << endl;
cout << "typeof(y):" << typeid(y).name() << endl;
}

int main() {
int a = 3;
double b = 1.2;
print<int, double>(a,b);
}

输出结果

1
2
typeof(x):i
typeof(y):d

结构体和模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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(); // (0, 1)

// double型用のPoint構造体
Point<double> p2 = { 2.3, 4.5 };
p2.print(); // (2.3, 4.5)
return 0;
}

输出结果

1
2
(0, 1)
(2.3, 4.5)

常数模版template <int x>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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;
}

输出结果

1
2
3, 2, 1
2, 3, 1

转载请注明来源 https://tianweiye.github.io