C++ auto와 decltype을 활용한 타입 추론

타입 추론의 필요성과 기본 개념

C++11에서는 변수의 타입을 자동으로 추론하는 auto 키워드와 함수 반환 타입을 표현하는 decltype이 추가되었습니다. 이 기능들은 코드의 가독성을 높이고 복잡한 타입 선언을 간소화하는 데 유용합니다.

auto 키워드

auto는 다른 언어에서와 마찬가지로 변수의 실제 타입을 자동으로 추론합니다. 이 키워드는 일종의 "자리 표시자" 역할을 하며, auto로 선언된 변수는 반드시 초기화되어야 컴파일러가 실제 타입을 유추할 수 있습니다.

기본 문법

auto 변수명 = 값;

사용 예제

#include <iostream>
using namespace std;

int main() {
    auto num1 = 3.14;      // double
    auto num2 = 520;       // int
    auto ch = 'a';         // char
    
    int temp = 110;
    auto* ptr1 = &temp;    // int*
    auto ptr2 = &temp;     // int*
    auto& ref = temp;      // int&
    auto val = temp;       // int
    
    const int const_val = 250;
    auto a1 = const_val;   // int (const 제거)
    const auto& a2 = const_val; // const int&
    
    return 0;
}

주의사항

auto는 포인터나 참조와 결합할 때 const, volatile 한정자를 보존합니다:

  • 변수가 포인터나 참조가 아닐 때: const, volatile 제거
  • 변수가 포인터나 참조일 때: const, volatile 보존

auto 사용 불가 경우

  1. 함수 매개변수로 사용 불가
  2. 클래스의 비정적 멤버 변수 초기화 불가
  3. 배열 정의 불가
  4. 템플릿 매개변수 추론 불가

auto의 활용

1. STL 컨테이너 순회

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<int, string> data;
    data.insert({1, "ace"});
    data.insert({2, "sabo"});
    data.insert({3, "luffy"});
    
    auto it = data.begin();  // 간결한 반복자 선언
    for (; it != data.end(); ++it) {
        cout << "키: " << it->first << ", 값: " << it->second << endl;
    }
    return 0;
}

2. 제네릭 프로그래밍

#include <iostream>
using namespace std;

class Type1 {
public:
    static int getValue() { return 10; }
};

class Type2 {
public:
    static string getValue() { return "hello"; }
};

template <class T>
void process() {
    auto result = T::getValue();  // 반환 타입 자동 추론
    cout << "결과: " << result << endl;
}

int main() {
    process<Type1>();
    process<Type2>();
    return 0;
}

decltype 키워드

decltype은 컴파일 시점에 표현식의 타입을 추론합니다. 변수 초기화 없이도 타입을 추론할 수 있으며, 표현식의 값을 계산하지 않습니다.

기본 사용법

int main() {
    int num = 10;
    decltype(num) var1 = 99;           // int
    decltype(num + 3.14) var2 = 3.14;  // double
    decltype(num) var3;                // int (초기화 없이 선언 가능)
    return 0;
}

추론 규칙

1. 일반 변수/표현식/클래스 표현식

표현식의 타입과 동일한 타입을 추론합니다.

2. 함수 호출

함수 반환 타입과 동일한 타입을 추론합니다.

3. 왼값 또는 괄호로 둘러싼 표현식

참조 타입을 추론하며, const/volatile 한정자를 보존합니다.

decltype 활용

#include <iostream>
#include <list>
using namespace std;

template <class Container>
class Processor {
public:
    void display(Container& cont) {
        for (iter = cont.begin(); iter != cont.end(); ++iter) {
            cout << *iter << " ";
        }
        cout << endl;
    }
private:
    decltype(Container().begin()) iter;  // 컨테이너의 반복자 타입 추론
};

int main() {
    list<int> numbers = {1, 2, 3, 4, 5};
    Processor<list<int>> proc;
    proc.display(numbers);
    return 0;
}

후행 반환 타입

템플릿 프로그래밍에서 매개변수 연산을 통해 반환 타입을 결정할 때 유용합니다.

#include <iostream>
using namespace std;

template <typename T, typename U>
auto calculate(T t, U u) -> decltype(t + u) {
    return t + u;
}

int main() {
    int x = 520;
    double y = 13.14;
    auto result = calculate(x, y);  // 타입 추론으로 간결한 호출
    cout << "결과: " << result << endl;
    return 0;
}

태그: C++ auto decltype 타입추론 템플릿

8월 16일 16:48에 게시됨