Learning
레슨 5 / 8·20분

Modern C++ (C++17/20)

auto와 타입 추론

Modern C++(C++11 이후)은 코드를 더 안전하고 간결하게 작성할 수 있는 다양한 기능을 도입했습니다. auto 키워드는 컴파일러가 타입을 자동으로 추론하게 하며, 복잡한 타입 선언을 간소화합니다.

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

int main() {
    // auto 타입 추론
    auto x = 42;           // int
    auto pi = 3.14;        // double
    auto name = string("C++");  // string

    // 복잡한 타입에서 특히 유용
    map<string, vector<int>> data;
    data["scores"] = {90, 85, 92};

    // auto 없이: map<string, vector<int>>::iterator it = data.begin();
    auto it = data.begin();  // 훨씬 간결!

    // 범위 기반 for + auto
    for (const auto& [key, values] : data) {
        cout << key << ": ";
        for (const auto& v : values) {
            cout << v << " ";
        }
        cout << endl;
    }

    return 0;
}

람다 표현식

cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    // 기본 람다
    auto greet = [](const string& name) {
        cout << "Hello, " << name << "!" << endl;
    };
    greet("C++");

    // 캡처 — 외부 변수 사용
    int threshold = 5;
    auto isAbove = [threshold](int x) {
        return x > threshold;
    };

    vector<int> nums = {1, 8, 3, 7, 2, 9, 4};

    // 알고리즘에 람다 활용
    // 조건에 맞는 요소 개수
    int count = count_if(nums.begin(), nums.end(), isAbove);
    cout << threshold << "보다 큰 수: " << count << "개" << endl;

    // 커스텀 정렬 (내림차순)
    sort(nums.begin(), nums.end(),
         [](int a, int b) { return a > b; });

    // 제네릭 람다 (C++14)
    auto multiply = [](auto a, auto b) { return a * b; };
    cout << multiply(3, 4) << endl;     // 12
    cout << multiply(2.5, 3.0) << endl; // 7.5

    return 0;
}

C++17/20 주요 기능

cpp
#include <iostream>
#include <optional>
#include <string>
#include <variant>
#include <string_view>
using namespace std;

// optional — 값이 있을 수도 없을 수도 있는 타입
optional<string> findUser(int id) {
    if (id == 1) return "Alice";
    if (id == 2) return "Bob";
    return nullopt;  // 값 없음
}

// string_view — 문자열의 읽기 전용 뷰 (복사 없음)
void printName(string_view name) {
    cout << "이름: " << name << endl;
}

int main() {
    // optional 사용
    auto user = findUser(1);
    if (user.has_value()) {
        cout << "찾음: " << user.value() << endl;
    }

    auto unknown = findUser(99);
    cout << unknown.value_or("알 수 없음") << endl;

    // 구조적 바인딩 (C++17)
    auto [a, b, c] = make_tuple(1, 2.0, "three");
    cout << a << ", " << b << ", " << c << endl;

    // if 초기화 문 (C++17)
    if (auto result = findUser(2); result) {
        cout << "사용자: " << *result << endl;
    }

    // string_view
    string fullName = "Kim Chulsoo";
    printName(fullName);  // 복사 없이 참조

    return 0;
}
  • auto — 컴파일러 타입 추론
  • lambda — 익명 함수 객체, [캡처](매개변수) { 본문 }
  • optional — 값이 없을 수 있는 타입 (C++17)
  • string_view — 문자열 읽기 전용 뷰, 복사 비용 없음 (C++17)
  • 구조적 바인딩 — auto [x, y] = pair (C++17)
  • constexpr if — 컴파일 타임 조건 분기 (C++17)
💡

Modern C++를 사용하면 코드가 더 안전하고 읽기 쉬워집니다. 컴파일러 옵션에서 -std=c++17 또는 -std=c++20을 설정하세요. GCC 9+, Clang 10+, MSVC 2019+에서 C++17을 지원합니다.