
- template <typename T>
: STL 클래스에서 타입을 나중에 지정하겠다고 명시하는 방법. 여기에서 T가 나중에 지정할 타입 이름이 된다.
예제코드)
#include <cstdio>
#include <string>
template <typename T>
class Myclass {
public:
T value;
};
template <typename T>
void swap(T* a, T* b) {
T tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int main() {
Myclass<int>* m = new Myclass<int>();
m->value = 100; // 여기서는 int
Myclass<std::string>* ms = new Myclass<std::string>();
ms->value = "Hello World"; // 여기서는 str
std::string value1 = "Hello";
std::string value2 = "World";
swap<std::string>(&value1, &value2);
printf("value1 : %s\n", value1.c_str());
printf("value2 : %s\n", value2.c_str());
return 0;
}

예제코드)
#include <cstdio>
#include <string>
template <typename T>
class Myarray {
public:
T* arrayItem; // 배열포인터
int count = 0;
int capacity = 8;
Myarray() {
arrayItem = new T[capacity];
}
virtual ~Myarray() { // 소멸자는 virtual을 붙여줘야한다. 잊지말기.
delete[] arrayItem;
}
void putValue(T value) {
if (capacity <= count) {
printf("배열의 캐파시티가 두배로 늘어났습니다\n");
T* newarray = new T[capacity * 2];
capacity = capacity * 2;
for (int i = 0; i < count; i++) {
newarray[i] = arrayItem[i];
}
delete[] arrayItem;
arrayItem = newarray;
}
arrayItem[count] = value;
count++;
}
};
int main() {
Myarray<int> m = Myarray<int>();
m.putValue(100);
m.putValue(200);
m.putValue(300);
m.putValue(400);
m.putValue(500);
m.putValue(600);
m.putValue(700);
m.putValue(800);
m.putValue(900);
for (int i = 0; i < m.count; i++) {
printf("%d\n", m.arrayItem[i]);
}
return 0;
}

*더 알아보기
이 STL 때문에 C++의 컴파일은 또 극악으로 느린 빌드/컴파일 타임을 갖게 됩니다. 하지만 빌드/컴파일 타임을 희생한 만큼 만들어진 프로그램의 퍼포먼스는 비슷한 코딩 방법을 채택하고 있는 그 어떤 언어들보다도 빠른 속도를 갖습니다.
++ 꿀팁 crtl + . 눌러서 누락된 내용 한번에 추가가능
과제형 문제)

sol)
#include <cstdio>
#include <string>
template <typename T>
class Myarray {
private:
T* arrayItem; // 배열포인터
int count = 0;
int capacity = 8;
public:
Myarray() {
arrayItem = new T[capacity];
}
virtual ~Myarray() { // 소멸자는 virtual을 붙여줘야한다. 잊지말기.
delete[] arrayItem;
}
void putValue(T value) {
if (capacity <= count) {
printf("배열의 캐파시티가 두배로 늘어났습니다\n");
T* newarray = new T[capacity * 2];
capacity = capacity * 2;
for (int i = 0; i < count; i++) {
newarray[i] = arrayItem[i];
}
delete[] arrayItem;
arrayItem = newarray;
}
arrayItem[count] = value;
count++;
}
int getCount() {
return count;
}
T getValue(int index) {
return arrayItem[index];
}
// value 값이 존재하는지 확인하는 함수
bool contains(T value) {
for (int i = 0; i < count; i++) {
if (value == arrayItem[i]) {
return true;
}
}
return false;
}
// 값을 변경
void replace(int index, T value) {
if (index < count) {
arrayItem[index] = value;
}
}
// 값을 삭제 (빈 공간을 채워줘야 한다.)
void erase(int index) {
for (int i = index; i < count - 1; i++) {
arrayItem[i] = arrayItem[i + 1];
}
count--;
}
};
int main() {
Myarray<int> m = Myarray<int>();
m.putValue(10);
m.putValue(11);
m.putValue(15);
m.putValue(20);
m.replace(2, 100);
if (m.contains(44)) {
printf("값을 포함하고 있습니다.");
}
else {
printf("포함 하고 있지 않습니다.");
}
return 0;
}