Machineboy空

Object-Oriented Data Structures # WEEK04 : Templates and Classes 본문

Computer/자료구조

Object-Oriented Data Structures # WEEK04 : Templates and Classes

안녕도라 2024. 2. 7. 10:35

4.5 Templates and Classes

C++ allows for us to use the power of templates in building our own classes and functions.

 

Templated Functions

A template variable is defined by declaring it before the beginning of a class or function:

//class
template <typename T>
class List{
	private:
    T data;
};

//function
template <typename T>
int max(T a, T b){
	if(a >b) {return a;}
    return b;
}

 

Compile-TIme Binding

Templated variables are checked at compile time, which allows for errors to be caught before running the program:

template <typename T>
T max(T a, T b){
	if(a>b) { return a;}
    return b;
}

// max(Cube(3),Cube(6)>> ERROR

Cube의 대소비교에 관한 것을 프로그래밍 해주지 않았으므로 에러가 난다.