템플릿(Template)
🖥️ 템플릿(Template)이란?
C++에서 * 제네릭 프로그래밍의 기초이며, 많은 데이터 구조와 알고리즘이 어떤 형식이든 동일하게 작동할 수 있게 해준다.
클래스 또는 함수의 작업을 정의하고, 그러한 작업이 어떤 구체적인 형식에서 작동해야 하는지를 사용자가 지정할 수 있다.
* 제네릭 프로그래밍(generic programming) : 데이터 형식에 의존하지 않고, 하나의 값이 여러 다른 데이터 타입들을 가지룻 있는 기술에 중점을 두어 재사용성을 높일 수 있는 프로그래밍 방식.
🖥️ 템플릿 사용 예시
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
//1. 기본
template<typename TValueType, typename TRetType> //typename은 의미있는 이름 사용.
TRetType Add(TValueType val1, TRetType val2)
{
TRetType ret = (TRetType)val1 + (TRetType)val2; //명시
return ret;
}
//2. 템플릿 특수화 : 특정한 자료형만 별도의 처리를 할 수 있도록 함.
template<>
string Added(string val1, string val2) //파라미터 자료형과 리턴 자료형이 같아야함.
{
return val1 + "_" + val2;
}
//3. 템플릿 타입의 포인터형 (레퍼런스형도 가능.)
template<typename TValueType>
TValueType* Added(TValueTypeT* val1, TValueType* val2)
{
*val1 = *val1 + *val2;
return val1;
}
int main()
{
//1.
float a = Add<int, float>(10, 20);
printf("a = %f\n", a); /// 30.000000
//2.
int c = Added<int>(10, 20);
printf("c = %d\n", c); /// 30
float d = Added<float>(3.14f, 3.14f);
printf("d = %f\n", d); /// 6.28
string e = Added<string>("abc", "def");
printf("e = %s\n", e.c_str()); ///abc_def
//3.
int f = 10, g = 20;
int* p = Added<int>(&f, &g);
printf("*p = %d\n", *p); // 30
return 0;
}
🖥️ 클래스 템플릿(Class Template)
템플릿은 함수 외에도 클래스에서도 사용할 수 있다. 멤버 함수는 클래스 템플릿 내부 및 외부에서 정의할 수 있으며, 클래스 외부에서 정의된 경우 함수 템플릿처럼 정의된다.
🖥️ 클래스 템플릿 사용 예시
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class Character
{
public:
void Set(T name)
{
this->name = name;
}
virtual void Print()
{
cout << "Character : " << name << endl;
}
protected:
T name;
};
class Player : public Character<int>
{
public:
void Print() override
{
printf("Player : %d\n", name);
}
};
class Monster : public Character<string>
{
public:
void Print() override
{
cout << "Monster : " << name << endl;
}
};
int main()
{
Character<string> character;
character.Set("Seony");
character.Print(); /// Character : Seony
Player player;
player.Set(10);
player.Print(); /// Player : 10
Monster monster;
poring.Set("Devil");
poring.Print(); /// Monster : Devil
return 0;
}
출처 :
* https://learn.microsoft.com/ko-kr/cpp/cpp/templates-cpp?view=msvc-170
* https://en.wikipedia.org/wiki/Generic_programming