๐Ÿ“ Coding Test Study/C++

C++ Template์ด๋ž€? ์ ์šฉ ๋ฐฉ๋ฒ•์€?

ibelieveinme 2021. 3. 1. 01:56
728x90

โ–ท C++ Template์ด๋ž€?

: int, double, long ๋“ฑ์˜ ์ž๋ฃŒํ˜•์— ๊ตฌ์• ๋ฐ›์ง€ ์•Š๊ณ  ๊ณตํ†ต๋œ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ๋†“๊ณ  ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์ •์˜ํ•ด๋‘๋Š” ๊ฒƒ

 

โ–ท C++ Document์—์„œ์˜ ์ •์˜

#include <algorithm>

template<class T>
const T& min (const T& a, const T& b)

 

โ–ท ์‚ฌ์šฉ๋ฒ•

#include <iostream>
#include <algorithm>
using namespace std;

template <typename T>
T sum(T a, T b){
    return a + b;
}

int main(){
    cout << sum<int>(1, 2) << endl;
    cout << sum<double>(1.2, 1.3) << endl;
    return 0;
}

; ๋ฉ”์ธํ•จ์ˆ˜์—์„œ ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ๋•Œ๋งˆ๋‹ค ์ž๋ฃŒํ˜•์„ ์ ์–ด์„œ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

; sum ํ•จ์ˆ˜๋Š” ํ•„์š”์—†๊ฒ ์ง€๋งŒ, ์ข€ ๋” ๋ณต์žกํ•œ ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•ด์•ผํ•  ๋•Œ ๋ฐ์ดํ„ฐํ˜•์„ ์‹ ๊ฒฝ์“ฐ์ง€ ์•Š๊ณ  ํ•จ์ˆ˜๋ฅผ ์žฌ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์žฅ์ ์ด ์žˆ๋‹ค.

728x90