이번 포스팅에 정리할 내용은 template 과 integral_constant 관련 내용이다.
C++ Template and integral_constant
integral_constant 는 템플릿을 이용하여 같은 상수이지만 타입으로 달라지는 방식을 이용하는 것이다. 말이 어렵다 코드를 보도록 하자.
#include <iostream>
using namespace std;
void func(int a)
{
wcout << "func called." << endl;
}
int main()
{
func(0);
func(1);
return 0;
}
위 코드에서 func() 으로 넘어가는 0 과 1 은 같은 integer 타입이다. 하지만 이것을 템플릿을 이용하여 다른 타입으로 만들 수 있다. 다음 코드를 보도록 하자.
#include <iostream>
using namespace std;
template <int N>
struct intType
{
enum { value = N };
};
void func(int a)
{
wcout << "func called." << endl;
}
int main()
{
intType<1> a;
intType<2> b;
func(a); ----> compile error !!
return 0;
}
위 코드에서 func(a) 부분에서 컴파일 에러가 발생하는데 이유는 intType 템플릿에 의해서 a 와 b는 int 타입이 아닌 것이다. 즉 intType<1>, intType<2> 이것 자체가 타입인 것이다. (템플릿에 의한 새로운 상수 타입은 컴파일 시점에 결정된다.)
위 방식을 이용하면 이전 포스팅에서 작성하였던 최소값 템플릿 함수를 완성시킬 수 있다. 다음 코드를 보도록 하자.
#include <iostream>
using namespace std;
template <int N>
struct intType
{
enum { value = N };
};
template <typename T>
struct isPointer{
enum { value = 0};
};
template <typename T>
struct isPointer<T*>{
enum { value = 1};
};
template <typename T>
T getMinInner(T v1, T v2, intType<1>)
{
return (*v1 < *v2) ? v1 : v2;
}
template <typename T>
T getMinInner(T v1, T v2, intType<0>)
{
return (v1 < v2) ? v1 : v2;
}
template <typename T>
T getMin(T v1, T v2)
{
return getMinInner(v1, v2, intType<isPointer<T>::value>() );
}
int main()
{
int a = 3, b = 1;
int c = getMin(a, b);
int* d = getMin(&a, &b);
return 0;
}
위 코드를 보면 getMin 함수가 T를 반환하도록 하였다. T 가 포인터로 들어오면 포인터로 반환하고 일반 변수로 들어오면 일반 변수로 반환한다. 이것이 가능한 것은 getMin 내부에서 integral_constant 를 이용하여 포인터와 그렇지 않을 경우 타입을 다르게 가져가서 완전 다른 함수가 호출되게 하였기 때문이다.
지난 정리 포스팅은
2022.01.11 - [프로그래밍/C/C++] - C++ template 과 type 추론
C++ template 과 type 추론
C++ template 과 type 추론 이번 포스팅 정리는 template 과 type 추론 관련해서 정리해 본다. 보통 우리는 최소값 구하는 함수를 아래와 같이 구현할지 모른다. #include template T GetMin(T a, T b) { return a..
nanze.tistory.com
'프로그래밍 > C/C++' 카테고리의 다른 글
[C++] 스마트포인터 shared_ptr - 정보공유의 장 (0) | 2022.01.15 |
---|---|
C++ template with member function (0) | 2022.01.13 |
C++ template 과 type 추론 (0) | 2022.01.11 |
C++ Perfect forwarding (std::forward 의 역할) (0) | 2022.01.08 |
C++ Universal reference & Reference Collapsing Rules (0) | 2022.01.07 |