19.1 — Template classes

주홍영·2022년 3월 22일
0

Learncpp.com

목록 보기
184/199

https://www.learncpp.com/cpp-tutorial/template-classes/

우리는 이전 챕터에서 function template에 대해서 다룬적 있다
function template은 다른 여러 타입으로도 function을 기능할 수 있게 도와주웠다
우리는 이러한 template이 할 수 있는 더 많은 것들에 대해서 살펴본다

Templates and container classes

우리는 클래스에 template을 접목해서 일반화된 container class를 만들 수 있다

Array.h:

#ifndef ARRAY_H
#define ARRAY_H

#include <cassert>

template <typename T> // added
class Array
{
private:
    int m_length{};
    T* m_data{}; // changed type to T

public:

    Array(int length)
    {
        assert(length > 0);
        m_data = new T[length]{}; // allocated an array of objects of type T
        m_length = length;
    }

    Array(const Array&) = delete;
    Array& operator=(const Array&) = delete;

    ~Array()
    {
        delete[] m_data;
    }

    void erase()
    {
        delete[] m_data;
        // We need to make sure we set m_data to 0 here, otherwise it will
        // be left pointing at deallocated memory!
        m_data = nullptr;
        m_length = 0;
    }

    T& operator[](int index) // now returns a T&
    {
        assert(index >= 0 && index < m_length);
        return m_data[index];
    }

    // templated getLength() function defined below
    int getLength() const;
};

// member functions defined outside the class need their own template declaration
template <typename T>
int Array<T>::getLength() const // note class name is Array<T>, not Array
{
  return m_length;
}

#endif

function template과 마찬가지로 class Array의 선언부 바로 위에
template < typename T >를 추가해서 T에 대해 우리가 조작할 수 있도록 한다
참고로 member function을 외부에서 define할 때
template < typename T >
int Array< T >::getLength() const
처럼 template과 클래스 이름의 뒤에 T를 추가해서 정의한다

여기 main함수에서 사용하는 예시이다

#include <iostream>
#include "Array.h"

int main()
{
	Array<int> intArray { 12 };
	Array<double> doubleArray { 12 };

	for (int count{ 0 }; count < intArray.getLength(); ++count)
	{
		intArray[count] = count;
		doubleArray[count] = count + 0.5;
	}

	for (int count{ intArray.getLength() - 1 }; count >= 0; --count)
		std::cout << intArray[count] << '\t' << doubleArray[count] << '\n';

	return 0;
}

Template classes in the standard library

우리가 class template에 대해서 살펴보았으므로
STL을 만들 때 왜 std::vector< int > 와 같은 형태로 type을 작성했는지 이해할 수 있다

Template classes in the standard library

일반 non-template 클래스에서처럼
class definition은 header file에서 하고
member function definition을 cpp에서 하면
template class에서는 문제가 발생한다

이를 해결하는 가장 쉬운 방법은 template class의 모든 code를 header file에서 하는 것이다
단점은 template class가 많은 다른 파일에서 사용되면 많은 local copy를 발생하게 된다
이는 compile과 link time을 증가 시킨다
만약 compile or link time이 문제가 되지 않는다면 위 방법이 가장 선호되는 방법이다

그외 여러가지 방법이 있지만 궁금하면 찾아보자
일단은 생략한다

profile
청룡동거주민

0개의 댓글