C++ 최신 기능 | "C++17/20/23" 핵심 정리
이 글의 핵심
C++ 최신 기능에 대해 정리한 개발 블로그 글입니다. #include <map> #include <string> using namespace std;
C++17 핵심 기능
1. Structured Binding
#include <map>
#include <string>
using namespace std;
int main() {
// pair 분해
pair<int, string> p = {1, "one"};
auto [id, name] = p;
cout << id << ": " << name << endl;
// map 순회
map<string, int> scores = {{"Alice", 90}, {"Bob", 85}};
for (const auto& [name, score] : scores) {
cout << name << ": " << score << endl;
}
// 배열 분해
int arr[] = {1, 2, 3};
auto [a, b, c] = arr;
}
2. if constexpr
template <typename T>
auto getValue(T t) {
if constexpr (is_pointer_v<T>) {
return *t; // 포인터면 역참조
} else {
return t; // 아니면 그대로
}
}
int main() {
int x = 10;
int* ptr = &x;
cout << getValue(x) << endl; // 10
cout << getValue(ptr) << endl; // 10
}
3. std::optional
#include <optional>
#include <string>
using namespace std;
optional<string> findUser(int id) {
if (id == 1) {
return "Alice";
}
return nullopt; // 값 없음
}
int main() {
auto user = findUser(1);
if (user) {
cout << "찾음: " << *user << endl;
} else {
cout << "없음" << endl;
}
// 또는
cout << user.value_or("Unknown") << endl;
}
4. std::variant
#include <variant>
#include <string>
using namespace std;
int main() {
variant<int, double, string> v;
v = 10;
cout << get<int>(v) << endl;
v = 3.14;
cout << get<double>(v) << endl;
v = "Hello";
cout << get<string>(v) << endl;
// 방문자 패턴
visit( {
cout << arg << endl;
}, v);
}
5. std::filesystem
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
// 디렉토리 순회
for (const auto& entry : fs::directory_iterator(".")) {
cout << entry.path() << endl;
}
// 파일 존재 확인
if (fs::exists("file.txt")) {
cout << "파일 있음" << endl;
}
// 파일 크기
auto size = fs::file_size("file.txt");
cout << "크기: " << size << " bytes" << endl;
}
C++20 핵심 기능
1. Concepts
#include <concepts>
#include <iostream>
using namespace std;
// 개념 정의
template <typename T>
concept Numeric = integral<T> || floating_point<T>;
// 개념 사용
template <Numeric T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add(1, 2) << endl; // OK
cout << add(1.5, 2.5) << endl; // OK
// cout << add("a", "b"); // 컴파일 에러!
}
2. Ranges
#include <ranges>
#include <vector>
#include <iostream>
namespace rng = std::ranges;
namespace vw = std::views;
int main() {
vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 짝수만 필터링하고 2배
auto result = v
| vw::filter( { return x % 2 == 0; })
| vw::transform( { return x * 2; });
for (int x : result) {
cout << x << " "; // 4 8 12 16 20
}
}
3. Coroutines
#include <coroutine>
#include <iostream>
using namespace std;
struct Generator {
struct promise_type {
int current_value;
Generator get_return_object() {
return Generator{handle_type::from_promise(*this)};
}
suspend_always initial_suspend() { return {}; }
suspend_always final_suspend() noexcept { return {}; }
suspend_always yield_value(int value) {
current_value = value;
return {};
}
void return_void() {}
void unhandled_exception() {}
};
using handle_type = coroutine_handle<promise_type>;
handle_type coro;
Generator(handle_type h) : coro(h) {}
~Generator() { if (coro) coro.destroy(); }
bool move_next() {
coro.resume();
return !coro.done();
}
int current_value() {
return coro.promise().current_value;
}
};
Generator counter() {
for (int i = 0; i < 5; i++) {
co_yield i;
}
}
int main() {
auto gen = counter();
while (gen.move_next()) {
cout << gen.current_value() << " ";
}
}
4. Modules (간단 예제)
// math.cppm
export module math;
export int add(int a, int b) {
return a + b;
}
// main.cpp
import math;
import std;
int main() {
std::cout << add(1, 2) << std::endl;
}
5. Three-way Comparison (<=>)
#include <compare>
#include <iostream>
using namespace std;
struct Point {
int x, y;
auto operator<=>(const Point&) const = default;
};
int main() {
Point p1{1, 2};
Point p2{1, 3};
cout << (p1 < p2) << endl; // 1
cout << (p1 == p2) << endl; // 0
cout << (p1 != p2) << endl; // 1
}
C++23 핵심 기능
1. std::print
#include <print>
int main() {
std::print("Hello, {}!\n", "World");
std::print("x = {}, y = {}\n", 10, 20);
}
2. Multidimensional Subscript
struct Matrix {
int data[3][3];
int& operator {
return data[i][j];
}
};
int main() {
Matrix m;
m[0, 1] = 5; // C++23
}
3. if consteval
consteval int sqr(int n) {
return n * n;
}
int main() {
constexpr int x = sqr(5); // 컴파일 타임
if consteval {
// 컴파일 타임에만 실행
} else {
// 런타임에 실행
}
}
실전 예시
예시 1: 모던 C++ 스타일
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
namespace rng = std::ranges;
namespace vw = std::views;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 짝수만 필터링, 제곱, 합계
auto sum = numbers
| vw::filter( { return x % 2 == 0; })
| vw::transform( { return x * x; })
| vw::common;
int result = rng::fold_left(sum, 0, std::plus<>());
cout << "결과: " << result << endl; // 220
}
예시 2: Concepts로 안전한 코드
#include <concepts>
#include <vector>
#include <iostream>
using namespace std;
template <typename T>
concept Container = requires(T t) {
{ t.begin() } -> same_as<typename T::iterator>;
{ t.end() } -> same_as<typename T::iterator>;
{ t.size() } -> convertible_to<size_t>;
};
template <Container C>
void printContainer(const C& container) {
for (const auto& item : container) {
cout << item << " ";
}
cout << endl;
}
int main() {
vector<int> v = {1, 2, 3};
printContainer(v); // OK
// printContainer(42); // 컴파일 에러!
}
예시 3: Optional로 안전한 에러 처리
#include <optional>
#include <string>
#include <iostream>
using namespace std;
optional<int> parseInteger(const string& str) {
try {
return stoi(str);
} catch (...) {
return nullopt;
}
}
int main() {
auto result = parseInteger("123");
if (result) {
cout << "파싱 성공: " << *result << endl;
} else {
cout << "파싱 실패" << endl;
}
// 체이닝
auto value = parseInteger("abc")
.or_else( { return optional<int>{0}; })
.transform( { return x * 2; });
cout << value.value() << endl; // 0
}
FAQ
Q1: 어떤 버전을 사용해야 하나요?
A:
- 새 프로젝트: C++20 이상
- 기존 프로젝트: C++17 이상
- 레거시: C++11 최소
Q2: 컴파일러 지원은?
A:
- GCC 11+, Clang 13+, MSVC 2019+ 권장
- cppref erence.com에서 지원 확인
Q3: 성능에 영향이 있나요?
A: 대부분 제로 오버헤드입니다. 오히려 더 최적화됩니다.
Q4: 기존 코드와 호환되나요?
A: 네, 하위 호환성이 유지됩니다.
Q5: Ranges가 왜 좋은가요?
A:
- 파이프라인 스타일
- 지연 평가
- 조합 가능
Q6: Concepts는 언제 사용하나요?
A:
- 템플릿 제약
- 명확한 에러 메시지
- 오버로딩 해결
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Optional 완벽 가이드 | nullopt·value_or·C++23 모나딕 연산·성능·실전 패턴
- C++ Union과 Variant | “타입 안전 공용체” 가이드
- C++ [[nodiscard]] 완벽 가이드 | 반환값 무시 방지·에러 코드·RAII·사유 메시지 [실전]
관련 글
- 모던 C++ (C++11~C++20) 핵심 문법 치트시트 | 현업에서 자주 쓰는 한눈에 보기