이 글에서는 C++ STL의 std::is_const 템플릿이 어떻게 동작하는지, 그리고 그 문법과 실제 활용 예제를 자세히 살펴보겠습니다.
C++의 is_const 템플릿은 특정 타입이 const 한정자(const-qualified)를 갖는 타입인지 아닌지를 판별할 때 사용됩니다.
const 한정자 타입이란?
타입의 값이 상수로 고정되어 있는 경우, 그 타입을 const 한정자 타입이라고 합니다. const로 선언된 데이터는 한 번 초기화되면 프로그램이 실행되는 동안 절대 변경하거나 수정할 수 없습니다.
문법(Syntax)
template <class T> is_const;
매개변수
이 템플릿은 T라는 단 하나의 타입 매개변수만 받으며, 해당 타입이 const 한정자인지 여부를 검사합니다.
반환 값
불리언(Boolean) 값을 반환합니다.
- 주어진 타입이 const 한정자 타입이면 true
- 그렇지 않으면 false
예제
입력: is_const<const int>::value; 출력: True 입력: is_const<int>::value; 출력: False
예제 코드 1: 기본 타입 검사
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_const template: ";
cout << "\nInt : "<<is_const<int>::value;
cout << "\nConst int : "<< is_const<const int>::value;
cout << "\nConst int& : "<< is_const<const int&>::value;
return 0;
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
checking for is_const template: Int : false Const int : true Const int& : false
참고: const int&(const에 대한 참조)가 false로 나오는 이유는, is_const가 검사하는 대상이 '참조 타입 자체'이기 때문입니다. 참조 자체에는 const 한정자가 적용되지 않으므로 결과는 false가 됩니다.
예제 코드 2: 포인터 타입 검사
#include <iostream>
#include <type_traits>
using namespace std;
int main() {
cout << boolalpha;
cout << "checking for is_const template: ";
cout << "\nFloat : "<<is_const<float>::value;
cout << "\nChar : "<<is_const<char>::value;
cout << "\nFloat *: "<<is_const<float*>::value;
cout << "\nChar *: "<<is_const<char*>::value;
cout << "\nConst int* : "<< is_const<const int*>::value;
cout << "\nint* const : "<< is_const<int* const>::value;
return 0;
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
checking for is_const template: Float : false Char : false Float *: false Char *: false Const int* : false int* const: true
결과 해석:
float*,char*: 포인터 자체에 const가 없으므로 falseconst int*: 포인터가 가리키는 값이 const일 뿐, 포인터 자체는 아니므로 falseint* const: 포인터 자체가 const이므로 true
C++17 이후: is_const_v 활용하기
C++17부터는 ::value를 붙이지 않고도 더 간결하게 사용할 수 있는 변수 템플릿 std::is_const_v<T>가 제공됩니다.
static_assert(is_const_v<const int>, "const int는 const 타입입니다"); static_assert(!is_const_v<int>, "int는 const 타입이 아닙니다");