`static_assert`는 C++11부터 제공되는 기능으로 컴파일 시간에 조건을 검사하여 컴파일 타임 에러를 발생시키는 역할을 수행하는 키워드이다.
이를 통해 컴파일 시간에 논리적인 조건을 확인하거나 특정한 제약을 검사하여 코드의 안전성을 높일 수 있다.
`static_assert`의 기본 구조는 다음과 같다.
static_assert(condition, message);
예시:
#include <iostream>
#include <type_traits>
template <typename T>
void print_Int() {
static_assert(std::is_integral<T>::value, "T must be integral type");
std::cout << "Size of " << typeid(T).name() << ": " << sizeof(T) << " bytes" << std::endl;
}
int main(void)
{
print_Int<int>();
// print_Int<double>(); // error
// print_size<std::string>(); // error: T must be an integral type
return 0;
}
위 코드에서 `print_Int` 함수는 템플릿으로 정의되어 있다.
`static_assert`를 사용하여 템플릿의 매개변수 `T`가 정수형 타입일 때만 컴파일을 허용하도록 제한하고 있다.
이렇게 함으로써 아래의 `double`와 `std::string`에서 에러를 발생시킨다.
`static_assert`는 코드의 안전성을 높이는데 도움을 주고, 특히 템플릿 메타 프로그래밍이나 일반 코드에서 조건을 검사하여 예기치 않은 문제를 방지하는데 사용된다.
[C++11] Variadic templates (0) | 2023.08.28 |
---|---|
[C++11] Initializer lists (0) | 2023.08.28 |
[C++11] auto (0) | 2023.08.26 |
[C++11] Lamda Expressions (0) | 2023.08.26 |
[C++11] decltype (0) | 2023.08.26 |