newind2000 2015. 6. 25. 16:53

================================ Outline ====================================

템플릿

- 템플릿이 2개 이상인 경우

- default 인자

- 특수화

- 비타입 인수

----------------------------------------------------------------------------

템플릿이 2개 이상인 경우

 

 #include <iostream>


using namespace std;

template <class T, class T2>
T add(T fNum, T2 iNum)
{
    return fNum + (T)iNum;
}


int main(void)
{
    float fNum = 2.1;
    int iNum = 3;

    fNum = add<floatint>(fNum, iNum);
    cout << fNum << endl;
    
    return 0;
}

 

 

default 인자

 

int add(int Num1, Num2 = 2)

{

return Num1 + Num2;

}

 

특수화

#include <iostream>
#include <stdio.h>

using namespace std;

template <class T>
void Swap(T &a, T &b)
{
    T t;
    t=a;
    a=b;
    b=t;
}

template <> void Swap<double> (double &a, double &b)
{
    int i,j;

    i = (int)a;
    j = (int)b;
    a = a - i + j;
    b = b - j + i;
}

int main(void)
{
    double a=1.2, b=3.4;
    printf("before a = %g, b = %g\n", a, b);
    Swap(a,b);
    printf("after a = %g, b = %g\n", a, b);

    return 0;
}

 

 

 

비타입 인수

 

템플릿의 인수는 통상적으로 타입이 오지만, 인자를 사용하고자 할 때 쓰는 것이 비타입인수이다.

#include <iostream>
#include <stdio.h>

using namespace std;

template <typename T, int N>
class Array
{
    private:
        T ar[N];
    public:
        void SetAt(int n, T v)
        {
            if (n < N && n >= 0)
                ar[n] = v;
        }
        T GetAt(int n)
        {
            return (n < N && n >= 0 ? ar[n]:0);
        }
};

int main(void)
{
    Array<int5> ari;
    ari.SetAt(11234);
    ari.SetAt(10005678);
    printf("%d\n", ari.GetAt(1));
    printf("%d\n", ari.GetAt(5));

    return 0;
}

템플릿 변수 안에 쓸 것이 없는 경우 <>표시만 해준다.

#include <iostream>

using namespace std;

template <typename T>
class smart
{
    public:
        static T Num;

};
template <typename T>
T smart<T>::Num;

template <>
int smart<int>::Num=100;

int main(void)
{
    smart<int> obj1;
    smart<short> obj2;
    cout <<obj1.Num << endl;
    cout <<obj2.Num << endl;
    
    return 0;
}

 

 

 

반응형