본문 바로가기
C++ 알고리즘/2. C++ 언어 review

템플릿

by Beijing_KingGod 2019. 9. 1.

template 이란?

-파라미터화된 타입으로 함수나 클래스를 정의할수있다.

-function template, class template

-타입에 관계없는 일반적(generic)인 코드를 제작할수있다.

#include <iostream>
using namespace std;
template <typename T> void swap_template(T& a, T& b){
	T temp = a;
	a= b;
	b= temp;
}
// class T -> T라는 타입이 있다고 가정한다.
// class T , typename T 둘다 됨

int main(){
	int first = 20, second=10;
	swap_template(first,second);
	cout<<"first"<<first<<" "<<"second"<<second<<endl;

	double d_first =1.25, d_second= 0.25;
	swap_template(d_first, d_second);
	cout<<"d_first"<<d_first<<" "<<"d_second"<< d_second<<endl;
	system("pause");
	return 0;	
}
first10 second20
d_first0.25 d_second1.25

 

'C++ 알고리즘 > 2. C++ 언어 review' 카테고리의 다른 글

힙 메모리 할당 c 와 c++  (0) 2019.09.01
포인터 와 레퍼런스 // call_by_value , call_by_reference  (0) 2019.09.01
래퍼런스 ( reference)  (0) 2019.09.01
포인터  (0) 2019.09.01

댓글