C, C++

Template

Yongs12 2023. 7. 1. 17:46

 
Template의 종류로는 
함수 템플릿과 클래스 템플릿으로 나뉜다.
 
함수 템플릿과 클래스 템플릿으로 나뉜다.
Template는 자료형에 국한되지 않고 모든 타입에 대해 받을 수 있다..
 
 
typeid 참고
ㄴ typeid(자료형).name()  을 통해 어떤 자료형인지 알 수 있다.
 

함수 템플릿 예시

// 모든 타입에 대해 받을 수 있음.
template<typename T>
void TemplatePrint(T value)
{
    std::cout << typeid(value).name() << std::endl;
}


// int 자료형만 받을 수 있음.
void NormalPrint(int value)
{
    std::cout << typeid(value).name() << std::endl;
}

class TestClass
{
public:
    TestClass(){}
};

int main()
{
    int a = 0;
    float b = 0.f;
    double c = 0;
    long long d = 0;
    TestClass e;

    TemplatePrint(a);
    TemplatePrint(b);
    TemplatePrint(c);
    TemplatePrint(d);
    TemplatePrint(e);
	
    return 0;
}

 

사용자가 만든 자료형도 다 받는다.

 
 

클래스 템플릿 예시

template<typename T>
class TestClass
{
public:
    TestClass(){}

public:
    void Print()
    {
        std::cout << typeid(_value).name() << "형 클래스" << std::endl;
    }

private:
    T _value;
};

class Test
{
public:
    Test(){}

};

int main()
{
    TestClass<int> intClass;
    TestClass<float> floatClass;
    TestClass<double> doubleClass;
    TestClass<Test> testClass;

    intClass.Print();
    floatClass.Print();
    doubleClass.Print();
    testClass.Print();

    return 0;
}