템플릿 기초

namu·2024년 3월 26일
템플릿: 함수나 클래스를 찍어내는 틀
1) 함수 템플릿
2) 클래스 템플릿

class Knight
{
public:
	// ...
    
public:
	int _hp = 100;
};

template<typename T>
void Print(T a)
{
	cout << a << endl;
}

template<typename T1, typename T2>
void Print(T1 a, T2 b)
{
	cout << a << " " << b << endl;
}

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

// 연산자 오버로딩 (전역함수 버전)
ostream& operator<<(ostream& os, const Knight&k)
{
	os << k._hp;
    return os;
}

// 템플릿 특수화
template<>
void Print(Knight a)
{
	cout << "Knight !!!!!!!!!!!!!!!!" << endl;
    cout << a._hp << endl;
}
template<typename T, int SIZE>
class RandomBox
{
public:
	T GetRandomData()
    {
    	int idx = rand() % SIZE;
        return _data[idx];
    }
    
public:
	T _data[SIZE];
};

// 템플릿 특수화
template<int SIZE>
class RandomBox<double, SIZE>
{
public:
	T GetRandomData()
    {
    	cout << "RandomBox Double" << endl;
    	int idx = rand() % SIZE;
        return _data[idx];
    }
    
public:
	T _data[SIZE];
};
profile
안녕하세요

0개의 댓글