본문 바로가기

프로그래밍 언어/C++

C++ Declaration의 5가지 효과

반응형

Declaration의 5가지 효과

✓ Static Assertion       → 컴파일 타임 검증
⚙️ Template Control      → 템플릿 제어  
🎯 Deduction Guide       → 타입 추론 도움
🏷️ Attributes            → 컴파일러 힌트
∅ Empty Declaration      → 효과 없음
Static Assertion
// ✓ Static Assertion - 컴파일 타임 검증
static_assert(sizeof(int) == 4, "int must be 4 bytes");
static_assert(std::is_integral_v<T>, "T must be integral");

// 조건이 false면 → 컴파일 에러!
Template Instantiation Control
// ⚙️ Template Instantiation 제어
template<typename T>
class MyClass { /*...*/ };

// 명시적 인스턴스화
template class MyClass<int>;  // 이 시점에 생성

// 명시적 인스턴스화 금지
extern template class MyClass<double>;  // 여기선 생성 안함
Deduction Guide
// 🎯 Deduction Guide - 생성자 타입 추론 가이드
template<typename T>
struct Container {
    Container(T t) { /*...*/ }
};

// Deduction guide 없이
Container c1(42);        // Container<int>

// 배열을 위한 deduction guide
template<typename T, size_t N>
Container(T(&)[N]) -> Container<T*>;

int arr[] = {1, 2, 3};
Container c2(arr);       // Container<int*> (가이드 덕분)
Attributes
// 🏷️ Attributes - 컴파일러/도구에 힌트
[[nodiscard]] int getValue() { return 42; }
// 반환값 무시하면 경고!

[[maybe_unused]] int debug_var = 0;
// 사용 안 해도 경고 안 나옴

[[deprecated("Use newFunc() instead")]]
void oldFunc() { /*...*/ }
Empty Declaration
// ∅ Empty Declaration - 아무 효과 없음
;  // 그냥 세미콜론

class MyClass {
    int x;
    ;  // 여기도 가능 (효과 없음)
    int y;
};

// 문법적으로 유효하지만 실제로는 아무것도 안 함
```

### 요약 슬라이드
```
Declaration = 단순 선언 이상!

컴파일 타임에 검증 ✓
템플릿 동작 제어 ⚙️
타입 추론 도움 🎯
메타 정보 제공 🏷️
(때론 아무것도 안 함 ∅)
728x90
반응형