[오버로딩]

 

일반적으로 함수는 이름이 같아도, 전달하는 매개 변수에 차이가 있다면 오버로딩이 이뤄집니다.

#include <iostream>

void Function(int Test)
{
    std::cout << Test;
}

void Function(bool Test)
{
    std::cout << Test;
}

void Function(int* Test)
{
    std::cout << Test;
}

int main()
{
    Function(10);       // 출력 : 10
    Function(true);     // 출력 : true
    int* Ptr = nullptr;
    Function();         // 출력 : 0000000000000000
}

 

 

[함수 template]

 

하지만 전달하는 자료형마다 일일이 함수를 작성해주는 것은 여간 번거로운 작업이 아닙니다. 이를 위해 template가 존재합니다.

#include <iostream>

template<typename DataType>
void Function(DataType Test)
{
    std::cout << Test;
}

int main()
{
    int* Ptr = nullptr;
    Function/*<int*>*/(Ptr);
    Function/*<int>*/(10);
    Function/*<bool>*/(true);
}

 

함수 template를 활용할 경우, 컴파일러가 인자 추론을 실시하여 해당 자료형에 맞는 함수를 컴파일 타임에 만들어줍니다. 인자 추론은 자료형이 확실한 경우(int, float, bool, pointer 등) 가능합니다.

 

 

[함수 template 특수화]

 

모두 동일한 동작을 하도록하지 않고, 특정한 인자값을 받는 경우 이를 다르게 활용하고 싶다면 template 특수화를 활용하면 됩니다. 아래와 같이 bool의 경우 다른 패턴을 활용하고 싶다면 template<> 키워드를 할당한 뒤 함수를 작성해주면 됩니다.

#include <iostream>

template<typename DataType>
void Function(DataType Test)
{
    std::cout << Test;
}
template<>
void Function(bool Test)
{
    std::cout << "bool 자료형 입니다.";
}

int main()
{
    int* Ptr = nullptr;
    Function(Ptr);      // 출력 : 0000000000000000
    Function(10);       // 출력 : 10
    Function(true);     // 출력 : bool 자료형 입니다.
}

'C++' 카테고리의 다른 글

[C++] union  (0) 2025.05.14
[C++] 클래스 template  (0) 2025.05.13
[C++] 람다  (0) 2025.05.13
[C++] 캐스팅(Casting)  (0) 2025.05.13
[C++] std::enable_shared_from_this와 shared_from_this()  (0) 2025.05.13

+ Recent posts