C++/Templates
2021. 3. 21. 23:58
함수 템플릿 (Function Templates)
template<typename T>
,template<class T>
의 형태로 템플릿을 선언할 수 있다.
예제
#include <iostream>
template<typename T>
T getMax(T x, T y)
{
return (x > y) ? x : y;
}
class Cents
{
int cents_;
public:
Cents(int cents = 0) { cents_ = cents; }
bool operator > (const Cents& c)
{
return (cents_ > c.cents_);
}
friend std::ostream& operator << (std::ostream& out, const Cents& cents)
{
out << cents.cents_ << " cents";
return (out);
}
};
int main()
{
using namespace std;
cout << getMax(1, 2) << endl;
cout << getMax(3.14, 1.592) << endl;
cout << getMax(1.0f, 3.4f) << endl;
cout << getMax('a', 'c') << endl;
cout << getMax(Cents(5), Cents(9)) << endl;
}
/* stdout
2
3.14
3.4
c
9 cents
*/
'C++ > Templates' 카테고리의 다른 글
C++ 클래스 템플릿 특수화 (Class Templates Specialization) (0) | 2021.03.22 |
---|---|
C++ 함수 템플릿 특수화 (Function Templates Specialization) (0) | 2021.03.22 |
C++ 자료형이 아닌 템플릿 매개변수 (Non-type Templates Parameters) (0) | 2021.03.21 |
C++ 클래스 템플릿 (Class Templates) (0) | 2021.03.21 |
C++ 템플릿 (Templates) (0) | 2021.03.21 |