하나의 형틀을 만들어서 다양한 코드를 생산해 내는 것을 템플릿이라 하는데,
함수를 찍어내기 위한 형틀을 함수 템플릿이라 한다.
template <typename T>
T get_max(T x, T y) {
if(x > y) return x;
else return y;
}
#include <iostream>
using namespace std;
template <typename T>
T get_sum(T x) {
x = x + 10;
return x;
}
int main() {
cout << get_sum(3) << endl;
return 0;
}
<aside> ➡️ 13
</aside>
#include <iostream>
using namespace std;
template <typename T>
T get_max(T x, T y) {
if (x > y) return x;
else return y;
}
int main() {
cout << get_max(1, 3) << endl;
cout << get_max(1.2, 3.9) << endl;
return 0;
}
<aside> ➡️ 3 3.9
</aside>
template <typename T>
T get_sum(T x) {
x = x + 10;
return x;
}
template <typename T>
T get_sum(T x, T y) {
if (x > y) return x;
else return y;
}
int main() {
cout << get_sum(3) << endl;
cout << get_sum(1.2, 3.9) << endl;
return 0;
}
<aside> ➡️ 3 3.9
</aside>
#include <iostream>
using namespace std;
template <typename T>
class Box {
T data; // T는 타입(type)을 나타낸다.
public:
Box() { }
void set(T value) {
data = value;
}
T get() {
return data;
}
void view() {
cout << data << endl;
}
};
int main() {
Box<int> b1;
b1.setBox(100);
b1.view();
Box<double> b2;
b2.setBox(3.14159);
b2.view();
return 0;
}
<aside> ➡️ 100 3.14159
</aside>