[C++] CPP Module 07

J_JEON·2022년 12월 23일
0

CPP

목록 보기
8/9

CPP Module 07

C++ template을 실습

ex00

  • 함수 템플릿을 정의해보고 호출해보기
  • template을 사용해 어떤 자료형이든 받아와서 사용할 수 있는 swap(a, b), min(a, b), max(a, b)함수 만들어보기
  • 이때 세가지 함수에 들어가는 두 인자는 같은 자료형이어야 함
  • 함수 템플릿의 정의와 선언은 모두 hpp 파일에서 이루어져야 함
template <typename T>
void swap(T &a, T &b)
{
	T temp;
	temp = a;
	a = b;
	b = temp;
}

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

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

ex01

  • 배열의 포인터를 받아와 배열의 각 요소들에 func 함수를 적용시켜줘야 함
  • 템플릿 함수를 함수 포인터로 받아와 사용
  • 템플릿 함수를 호출 시 자료형을 지정해주어야 하지만 첫 인자에서 자료형이 정해진다면 지정해주지 않아도 됨
template <typename T>
void inc(T &target)
	target++;

template <typename T>
void inc(const T &target)
	std::cout << target << " is const type!" << std::endl;

template <typename T>
void print(T &target)
	std::cout << target << std::endl;

template <typename T>
void iter(T *array, size_t array_len, void (*func)(T &))
{
	if (array == NULL || func == NULL)
		return ;
	for(size_t i = 0 ; i < array_len ; i++)
		func(array[i]);
}

template <typename T>
void iter(const T *array, const size_t array_len, void (*func)(const T &))
{
	if (array == NULL || func == NULL)
		return ;
	for(size_t i = 0 ; i < array_len ; i++)
		func(array[i]);
}

ex02

  • 클래스 템플릿 Array를 정의
  • 파라미터가 없는 생성자는 빈 Array를 생성
  • 파라미터로 unsigned int를 받아왔다면 해당 갯수만큼의 인자를 가진 Array 생성
  • OCCF를 준수하여 작성
  • []를 사용해 인자에 접근할 수 있도록 연산자 재정의를 해주어야 함
  • []연산자 재정의시 const와 non-const 두가지 모두를 만들어주어야 함
  • 잘못된 인자 접근을 한다면 exception을 throw
profile
늅늅

0개의 댓글