C++ templates
https://jun-13.tistory.com/148
[C++] templates
C++ templates ์ฝ๋์ ์ผ๋ฐํ์ ์ฌ์ฌ์ฉ์ ์ํ ๊ฐ๋ ฅํ ๋ฉ์ปค๋์ฆ์ ์ ๊ณตํ๋ ๊ธฐ๋ฅ // templates function template T add(T a, T b) { return a + b; } int main() { // intํ ์ธ์๋ฅผ ๊ฐ๋ ํจ์ ํธ์ถ std::cout
moaoh.dev
Exercise 00: Start with a few functions
what is templates??
// templates function
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
// intํ ์ธ์๋ฅผ ๊ฐ๋ ํจ์ ํธ์ถ
std::cout << add(5, 3) << std::endl;
// doubleํ ์ธ์๋ฅผ ๊ฐ๋ ํจ์ ํธ์ถ
std::cout << add(3.14, 2.71) << std::endl;
return 0;
}
์์ ๊ฐ์ ํ์์ฒ๋ผ template <typename T> ์ด๋ผ๋ ๊ธฐ๋ฅ์ ์ฌ์ฉํ๋ฉด ์ด๋ ํ ํ์ ์ด๋ ์ ๋์ ์ผ๋ก ๋์ํ์ฌ ํ๋์ ํจ์๋ก ๊ฐ์ ์ฒ๋ฆฌํ ์ ์๋ค.
์์ ๊ฐ์ template๋ผ๋ ๊ฐ๋ ์ ์์๋ณด๊ณ ์ฌ์ฉํด๋ณด๋ ๊ณผ์
Exercise 01: Iter
template <typename T>
void print(T a, T b) {
std::cout << "a :" << a << std::endl;
std::cout << "b :" << b << std::endl;
}
int main() {
print(5, "hello"); // error
return 0;
}
์์ ๊ฐ์ด print(5, “hello”) ํ์์ผ๋ก ํ๋๋ int ํ๋๋ str ๋ก ์ถ๋ ฅ์ ํ๊ณ ์ถ์๋ template์ด๋ผ๊ณ ๋ฐ๋ก ๋์ ์ ํด๋ฒ๋ฆฌ๋ฉด ์ค๋ฅ๊ฐ ๋ฐ์์ ํด๋ฒ๋ฆฐ๋ค.
๊ทธ ์ด์ ๋ ํ๋์ typename์ ํ๋์ ํ์ ๋ง ๋ฐ์ ์ ์๊ธฐ ๋๋ฌธ์ ์ด๋ฌํ ๋ฌธ์ ๊ฐ ๋ฐ์์ด ๋๋๋ฐ ์์ ๊ฐ์ ์ํฉ์ ํด๊ฒฐํ ๋ ค๋ฉด
template <typename T, typename U>
void print(T a, U b) {
std::cout << "a :" << a << std::endl;
std::cout << "b :" << b << std::endl;
}
int main() {
print(5, "hello"); // OK!
return 0;
}
template์ typename์ ์ถ๊ฐํด์ ์ค์ ์ ํด์ฃผ๋ฉด ์ถ๊ฐํ ๊ฐ์๋งํผ ๋ค์ํ type์ ๋ฐ์ ์ ์๊ฒ ๋๋ค.
ํด๋น ๊ฐ๋ ์ ์ฌ์ฉํ์ฌ ํด๋น ๋ฌธ์ ์ ์ ๊ทผํ์ฌ ํ ์ ์๋ ๋ฌธ์ ์๋ค.
Exercise 02: Mutated abomination
ํด๋น ๋ฌธ์ ์์๋ ์ฐ์ ์ ์ผ๋ก main๋ฌธ์ด ์ฃผ์ด์ง๊ณ ํด๋น ์ฝ๋๋ฅผ ์คํํ์๋ ์ ์์ ์ผ๋ก ๋์์ ํ๊ณ ์ฌ๋ฐ๋ฅธ ๊ฐ์ด ๋์์ผํ๋ค.
*.tpp ํด๋น ๋ฌธ์ ์์๋ ์ฒ์๋ณด๋ tpp๋ผ๋ ํ์ฅ์์ ํ์ผ์ ์์ฑ ํ ์ ์๊ฒ ํด์ฃผ๋๋ฐ ์ด ํ์ผ์ด ๋ฌด์์ธ์ง ์ฐพ์๋ณด๋ ๋ณดํต *.hpp์ ์ ์ธ์ด ๋์ด์๋ class๋ฅผ *.cpp์ ์ฎ๊ฒจ์ ์ ์ธ๊ณผ ์ ์๋ฅผ ๋ถ๋ฆฌํ ์ ์๋๋ฐ.
template์ ๊ฒฝ์ฐ์๋ *.cpp๋ก ๋ถ๋ฆฌ๋ฅผ ์๋ํ ๊ฒฝ์ฐ ์ปดํ์ผ ์์ ์ด๋ฅผ ์ ํํ๊ฒ ์ธ์ํ์ง ๋ชปํ๋ค๊ณ ํ๋ค. ๊ทธ๋์ *.tpp๋ผ๋ ํ์ฅ์๋ฅผ ์ฌ์ฉํด์ผ ํ์ผ์ ๋ถ๋ฆฌํ ์ ์๋ค๊ณ ํ๋ค.
int *a = new int();
int* a = new int[10];
์์ ๊ฐ์ ํ์์ผ๋ก *์ธ ๊ฐ์ ๋ฐฐ์ด์ ํ ๋นํ ์ ์๋ค.
ex02์์ T *array ํ์์ ๋ฐฐ์ด์ ๋ง๋ค์ด์ผํ๋ฏ๋ก T array = new T[size]; ํ์์ผ๋ก ํ ๋น์ ํ์ฌ ์งํํ ์ ์๋ค.
'42seoul > projects' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[CPP Module] 08 (0) | 2024.03.13 |
---|---|
[C++] templates (0) | 2024.03.13 |
[CPP Module] 06 (0) | 2024.03.13 |
[C++] casts (0) | 2024.03.13 |
[CPP Module] 05 (0) | 2024.03.13 |