(C++)14장 클래스 템플릿

1. 템플릿 클래스

#include<iostream>
#include<vector>

using namespace std;

template<typeame T>

class MyArray
{
 private:
  vector<T> list;

 public:
  void add_list(T const&);
  void delete_last_list(void);
  void show_list(void);
};

template<typename T>

void MyArray<T>::add_list(T const& element)
{
 list.push_back(element);
}

int main(void)
{
 MyArray<int> array1;
array1.add_list(1);

}

----->>>>>함수 템플릿과 비슷하지만 우선 클래스 멤버 함수를 정의할 때에도 template<typename T>를 다시 정의해야 한다 또한
MyArray::add_list(T const& element)가 아니라 MyArray<T>::add_list(T const& element)로
<T>가 정의 되어 있어야 한다.
또한 메인 함수에서는 MyArray<int> array1, MyArray<double> array2,가 되어야 한다.


2.1 템플릿 파라미터

여태까지 템플릿 파라미터가 typename으로 시작했지만 그렇지 않은 때도 있다.
이것을 non-type템플릿 파라미터라고 하는데 정수형 값, 나열형 값, 포인터 값, 참조형 변수와 같은 것들이다.

template <typename T,int init>

예제)
#include<iostream>
#include<vector>

using namespace std;
template<typename T,int init>

class MyArray
{
 private:
  vector<T> list;

 public:
  MyArray()
 {
   for(int i=0;i<init;i++)
  {
    list.push_back(i);
  }
  }

 void add_list(T const&);
 void delete_last_list(void);
 void show_list(void);
};

template<typename T,int init>
void MyArray<T,init>::add_list(T const& element)
{
 list.push_back(element);
}

template<typename T,int init>
void MyArray<T,init>::delete_last_list(void)
{
 list.pop_back();
}

template<typename T,int init>
void MyArray<T,init>::show_list(void)
{
  for(typename vector<T>::iterator i=list.begin();i!=list.end();i++)
  cout<<*i<<endl;
}
}


int main(void)
{
  MyArray<double,3> myArray1;
  MyArray<double,5> myArray2;
}


--------------->>>>>>>>>>컴파일러는 myArray1과 myArray2를 위해 전혀다른 클래스 타입을 정의한다.

템플릿 파라미터는 디폴트값으로 정의 할 수도 있다.

template<typename T=int>
라고 하고 메인에서
MyArray<> array2;로 하게 되면 디폴트값인 int로 정의 된다.
만약 MyArray<double> array3;로 하면 double형으로 정의 된다.

non-type템플릿 파라미터도 역시 디폴트 값을 지정 할 수 있다.
template<typename T=int,int init=3>


********주의 할 점은 디폴트 값은 제일 처음 템플릿 파라미터를 정의한 곳에서 한번만 해야 한다는 것이다.


2.2 클래스 템플리의 특수화

함수 템플릿의 특수화와 유사하다.

예제)
template<>
class MyArray<int>
{
 private:
  vector<int> list;
 public:
  void add_list(int const&);
  void delete_last_visit(void);
  void show_list(void);
};

void MyArray<int>::add_list(int const& element)
{
 list.push_back(element);
}

void MyArray<int>::delete_last_list(void)
{
 list.pop_back();
}

int main()
{
 MyArray<int> array1;
}

댓글

이 블로그의 인기 게시물

(네트워크)폴링방식 vs 롱 폴링방식

(ElasticSearch) 결과에서 순서 정렬

(18장) WebSocekt과 STOMP를 사용하여 메시징하기