CS/C++

[Mastering C++ Programming] - Class template

sliver__ 2022. 12. 6. 22:44
728x90
  • C++ template은 함수 템플릿 개념을 클래스로 확장하고 객체 지향 일반 코드를 작성할 수 있도록 합니다.
  •  클래스 템플릿을 사용하면 템플릿 유형 표현식을 통해 클래스 수준에서 데이터 유형을 매개변수화할 수 있습니다. 
  • 코드 예제는 아래와 같습니다.
//myalgorithm.h
#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>
using namespace std;

template <typename T, int size>
class MyAlgorithm {

public:
        MyAlgorithm() { } 
        ~MyAlgorithm() { }

        
        void sort( array<T, size> &data ) {
             for ( int i=0; i<size; ++i ) {
                 for ( int j=0; j<size; ++j ) {
                     if ( data[i] < data[j] )
                         swap ( data[i], data[j] );
                 }
             }
        }

        void sort ( T data[size] );

};

template <typename T, int size>
inline void MyAlgorithm<T, size>::sort ( T data[size] ) {
       for ( int i=0; i<size; ++i ) {
           for ( int j=0; j<size; ++j ) {
               if ( data[i] < data[j] )
                  swap ( data[i], data[j] );
           }
       }
}
#include "myalgorithm.h"

int main() {

    MyAlgorithm<int, 10> algorithm1;

    array<int, 10> a = { 10, 5, 15, 20, 25, 18, 1, 100, 90, 18 };

    cout << "\nArray values before sorting ..." << endl;
    copy ( a.begin(), a.end(), ostream_iterator<int>(cout, "\t") );
    cout << endl;

    algorithm1.sort ( a );

    cout << "\nArray values after sorting ..." << endl;
    copy ( a.begin(), a.end(), ostream_iterator<int>(cout, "\t") );
    cout << endl;

    MyAlgorithm<double, 6> algorithm2;
    double d[] = { 100.0, 20.5, 200.5, 300.8, 186.78, 1.1 };

    cout << "\nArray values before sorting ..." << endl;
    for(int i=0;i<6;i++)
    {
        cout << d[i] << "\t";
    }
    cout << endl;

    algorithm2.sort ( d );

    cout << "\nArray values after sorting ..." << endl;
    for(int i=0;i<6;i++)
    {
        cout << d[i] << "\t";
    }
    cout << endl;

    return 0;

}

 

  • 결과는 아래와 같습니다.
Array values before sorting ...
10  5   15   20   25   18   1   100   90   18

Array values after sorting ...
1   5   10   15   18   18   20   25   90   100

Array values before sorting ...
100   20.5   200.5   300.8   186.78   1.1

Array values after sorting ...
1.1     20.5   100   186.78  200.5  300.8
728x90