⭐ Programming/C++

[C++] 템플릿(Template) 1: 함수 템플릿

Designerd 2022. 4. 16. 16:38

  템플릿 기초 1

 

인프런 Rookiss님의 'Part1: C++ 프로그래밍 입문' 강의를 기반으로 정리한 필기입니다. 
😎[C++과 언리얼로 만드는 MMORPG 게임 개발 시리즈] Part1: C++ 프로그래밍 입문 강의 들으러 가기!

 

 


 

템플릿이란?

 

템플릿 : 함수나 클래스를 찍어내는 틀
 

 

템플릿 종류

  1. 함수 템플릿
  2. 클래스 템플릿

 

 

함수 템플릿 기초

 

#include <iostream>
using namespace std;

template<typename T>
void Print(T a)
{
    cout << a << endl;
}

int main()
{
    Print<int>(50);  // 명시적으로 <int>라고 적어줄 수도 있다
    Print(50.0f);
    Print(50.0);
    Print("Hello World");

    return 0;
}

 

 


 

 

함수 템플릿 

 

#include <iostream>
using namespace std;

class Knight {
public:
    // ...
public:
    int _hp = 100;
};

template<typename T>
void Print(T a)
{
    cout << a << endl;
}

template<typename T1, typename T2>
void Print(T1 a, T2 b)
{
    cout << a << " " << b << endl;
}

template<typename T>
T Add(T a, T b)
{
    return a + b;
}

// 연산자 오버로딩 (전역함수 버전)
ostream& operator<<(ostream& os, const Knight& k)
{
    os << k._hp;
    return os;
}

int main()
{
    Print<int>(50);  // 명시적으로 <int>라고 적어줄 수도 있다
    Print(50.0f);
    Print(50.0);
    Print("Hello World");
    
    Print("Hello ", 100);

    int result1 = Add(1, 2);
    float result2 = Add<float>(1.11f, 2.22f);

    Knight k1;
    Print(k1);

    return 0;
}


 

 

함수 템플릿 특수화

 

#include <iostream>
#include <iostream>
using namespace std;

class Knight {
public:
    // ...
public:
    int _hp = 100;
};

template<typename T>
void Print(T a)
{
    cout << a << endl;
}


// 템플릿 특수화
template<>
void Print(Knight a)
{
    cout << "Knight !!!!!!!" << endl;
    cout << a._hp << endl;
}


template<typename T1, typename T2>
void Print(T1 a, T2 b)
{
    cout << a << " " << b << endl;
}

template<typename T>
T Add(T a, T b)
{
    return a + b;
}

// 연산자 오버로딩 (전역함수 버전)
ostream& operator<<(ostream& os, const Knight& k)
{
    os << k._hp;
    return os;
}

int main()
{
    Print<int>(50);  // 명시적으로 <int>라고 적어줄 수도 있다
    Print(50.0f);
    Print(50.0);
    Print("Hello World");

    int result1 = Add(1, 2);
    float result2 = Add<float>(1.11f, 2.22f);

    Knight k1;
    Print(k1);


    return 0;
}