프로그래밍/C,C++

[Modern C++20] 🚀주요 특징 & 설명

GONII 2025. 4. 16. 09:33

 

✅ 1. Concepts – 템플릿 타입 제약

template<typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> std::convertible_to<T>;
};

template<Addable T>
T add(T a, T b) { return a + b; }
  • 템플릿에 조건을 부여할 수 있음
  • 컴파일 에러가 명확해짐, 가독성 증가
  • enable_if, SFINAE 대체 가능

✅ 2. Modules – 헤더보다 더 나은 코드 구성

// math.ixx
export module math;
export int add(int a, int b);
// main.cpp
import math;
  • #include 대신 import
  • 컴파일 속도↑, 중복 include 문제 해결
  • 대규모 프로젝트에서 효과적

✅ 3. Coroutines – 비동기 코드 간결하게

#include <coroutine>

task<int> getData() {
    co_return 42;
}
  • co_await, co_yield, co_return 사용
  • 비동기/지연 실행 코드 작성이 깔끔해짐
  • 예: 네트워크 요청, 게임 루프, async 작업

✅ 4. Ranges – 함수형 스타일 반복 처리

#include <ranges>
#include <vector>
#include <iostream>

std::vector<int> v = {1, 2, 3, 4, 5};
for (int n : v | std::views::filter([](int x) { return x % 2 == 0; })) {
    std::cout << n << '\n';
}
  • | 연산자로 filter, map, take 등 체이닝 가능
  • STL 범위 기반 루프를 더 강력하게 만듦

✅ 5. <=> 삼중 비교 연산자 (Spaceship Operator)

#include <compare>

struct MyType {
    int value;
    auto operator<=>(const MyType&) const = default;
};
  • 자동으로 <, ==, >, != 생성
  • 정렬/비교 연산 쉽게 자동화 가능

✅ 6. consteval, constinit – 컴파일 타임 실행/초기화

consteval int square(int x) { return x * x; }
constinit int global = 42;
  • consteval: 컴파일 타임에 반드시 실행
  • constinit: 정적 변수 반드시 초기화

✅ 7. std::format – Python 스타일 문자열 포맷팅

#include <format>
std::string msg = std::format("Hello, {}!", "world");
  • printf보다 안전하고 직관적
  • 문자열 조작이 매우 쉬워짐

✅ 8. std::span / std::string_view 강화

void print(std::span<int> arr) {
    for (int x : arr) std::cout << x << '\n';
}
  • std::span: 배열이나 vector를 포인터처럼 다룰 수 있게
  • std::string_view: 문자열 복사 없이 읽기 전용 참조

✅ 9. constexpr 범위 대폭 확대

constexpr int factorial(int n) {
    if (n <= 1) return 1;
    else return n * factorial(n - 1);
}
  • std::vector, std::string 등 컨테이너도 constexpr 사용 가능!
  • 컴파일 타임 계산을 더 많이 할 수 있게 됨

✅ 10. 템플릿 파라미터 단순화 (Class NTTP 확장)

template <auto N>
void printNTTP() {
    std::cout << N << '\n';
}

printNTTP<42>(); // OK
  • 이전에는 기본 타입만 가능했지만 이제는 클래스, 람다 등도 템플릿 인자 가능!

🔚 요약 표: C++20 주요 기능 한눈에 보기

기능 설명
Concepts 템플릿 타입 제약 조건 정의
Modules #include 대체, 빠른 컴파일
Coroutines co_await, 비동기 코드
Ranges STL 함수형 파이프라인 처리
<=> 삼중 비교, 비교 연산 자동화
consteval 컴파일 타임 함수
constinit 정적 초기화 강제
std::format 문자열 포맷팅, printf 대체
constexpr 확장 STL 컨테이너도 컴파일 타임 사용 가능
NTTP 개선 auto/class 템플릿 인자 지원
반응형