이 글에서는 C++ STL의 std::is_arithmetic 템플릿의 동작 원리, 문법, 그리고 실제 사용 예제를 살펴보겠습니다.
is_arithmetic 템플릿은 주어진 타입 T가 산술(arithmetic) 타입인지 여부를 컴파일 시점에 확인하는 데 사용되는 타입 특성(type trait)입니다.
산술 타입이란 무엇인가?
C++에서 산술 타입은 크게 두 가지 범주로 나뉩니다.
- 정수형(integral types) — 정수를 표현하는 타입으로, 다음과 같은 종류가 있습니다.
- char
- bool
- int
- long
- short
- long long
- wchar_t
- char16_t
- char32_t
- 부동소수점형(floating point types) — 소수 부분을 저장할 수 있는 타입입니다.
- float
- double
- long double
즉, is_arithmetic 템플릿은 지정된 타입 T가 위 두 범주에 속하는 산술 타입인지 검사하고, 그 결과에 따라 true 또는 false를 반환합니다.
문법
template <class T> is_arithmetic;
매개변수
이 템플릿은 타입 T 하나만을 매개변수로 받으며, 해당 타입이 산술 타입인지 여부를 검사합니다.
반환 값
이 템플릿은 bool 타입의 값을 반환하며, true 또는 false 중 하나입니다. 주어진 타입이 산술 타입이면 true를, 그렇지 않으면 false를 반환합니다.
예제 1: 기본 개념
Input: is_arithmetic<bool>::value;
Output: True
Input: is_arithmetic<class_a>::value;
Output: false
예제 2: 클래스 타입과 기본 타입 비교
#include <iostream>
#include <type_traits>
using namespace std;
class TP {
};
int main() {
cout << boolalpha;
cout << "checking for is_arithmetic template:";
cout << "\nTP class : "<< is_arithmetic<TP>::value;
cout << "\n For Bool value: "<< is_arithmetic<bool>::value;
cout << "\n For long value : "<< is_arithmetic<long>::value;
cout << "\n For Short value : "<< is_arithmetic<short>::value;
return 0;
}
출력 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
checking for is_arithmetic template:
TP class : false
For Bool value: true
For long value : true
For Short value : true
사용자가 정의한 TP 클래스는 산술 타입이 아니므로 false가 출력되고, bool, long, short는 모두 정수형에 속하므로 true가 출력됩니다.
예제 3: 포인터 타입 검사
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_arithmetic template:";
cout << "\nInt : "<< is_arithmetic<int>::value;
cout << "\nchar : "<< is_arithmetic<char>::value;
cout << "\nFloat : "<< is_arithmetic<float>::value;
cout << "\nDouble : "<< is_arithmetic<double>::value;
cout << "\nInt *: "<< is_arithmetic<int*>::value;
cout << "\nchar *: "<< is_arithmetic<char*>::value;
cout << "\nFloat *: "<< is_arithmetic<float*>::value;
cout << "\nDouble *: "<< is_arithmetic<double*>::value;
return 0;
}
출력 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
checking for is_arithmetic template:
Int : true
Char : true
Float : true
Double : true
Int * : false
Char *: false
Float *: false
Double *: false
여기서 주목할 점은 포인터 타입(int*, char* 등)은 기본 타입이 산술 타입이라 하더라도 포인터 자체는 산술 타입이 아니기 때문에 false를 반환한다는 것입니다. 이처럼 is_arithmetic은 템플릿 메타프로그래밍에서 타입 제약 조건을 검사하거나 조건부 컴파일 로직을 구성할 때 유용하게 활용됩니다.