42seoul/projects
[C++] templates
moaoh
2024. 3. 13. 15:19
C++ 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> ์ด๋ผ๋ ๊ธฐ๋ฅ์ ์ฌ์ฉํ๋ฉด ์ด๋ ํ ํ์ ์ด๋ ์ ๋์ ์ผ๋ก ๋์ํ์ฌ ํ๋์ ํจ์๋ก ๊ฐ์ ์ฒ๋ฆฌํ ์ ์๋ค.
// templates class
template <typename T>
class Pair {
public:
T first;
T second;
Pair(T a, T b) : first(a), second(b) {}
};
์์ ๊ฐ์ด class์๋ ์ ์ฉ๊ฐ๋ฅ.