Skip to content

Latest commit

 

History

History

05_modern_cpp

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

README.md

Modern C++ - Features from C++11 to C++23

"Modern C++ is simpler, safer, and more expressive."


Overview

This section covers modern C++ features that have transformed the language from its C-like roots into a powerful, expressive programming language suitable for modern software development.

Core Topics

C++11 - The Foundation of Modern C++

  • Type deduction (auto, decltype)
  • Range-based for loops
  • Lambda expressions
  • Move semantics
  • Smart pointers (unique_ptr, shared_ptr)
  • constexpr and noexcept
  • Threads and concurrency basics

Key Changes:

  • Revolutionized C++ development
  • Introduced move semantics
  • Made memory management safe
  • Added functional programming tools

C++14 - Refinements

  • Relaxed constexpr
  • Generic lambdas
  • Return type deduction
  • Binary literals
  • Digit separators
  • make_unique

Key Changes:

  • Made constexpr more useful
  • Improved lambda expressiveness
  • Added convenience features

C++17 - Major Improvements

  • Structured bindings
  • std::optional, std::variant, std::any
  • std::string_view
  • if constexpr
  • Folding expressions
  • Parallel algorithms
  • std::filesystem
  • Class template argument deduction (CTAD)

Key Changes:

  • Safer code with optional/variant
  • Zero-overhead string views
  • Compile-time conditionals
  • Filesystem support

C++20 - The Big Update

  • Concepts
  • Ranges
  • Coroutines
  • Modules
  • Three-way comparison (<=>)
  • Calendar and time zones
  • Formatting library (std::format)
  • Span (std::span)
  • std::expected (C++23 preview)

Key Changes:

  • Type constraints with concepts
  • Functional ranges
  • Asynchronous coroutines
  • Modern modules
  • Improved generics

C++23 - Latest Features

  • std::expected
  • std::flat_map, std::flat_set
  • Deducing this
  • Standard library modules
  • Print functions (std::print)
  • Improvements to ranges and views

Key Changes:

  • Error handling improvements
  • Better associative containers
  • Member function adaptors
  • Simplified output

Modern C++ Feature Timeline

C++98  ──────┐
              │
C++11  ───────┼─► auto, lambdas, smart pointers, move semantics
              │
C++14  ───────┼─► Generic lambdas, return type deduction
              │
C++17  ───────┼─► Structured bindings, optional, variant, string_view
              │
C++20  ───────┼─► Concepts, ranges, coroutines, modules
              │
C++23  ───────┴─► expected, flat_map, deducing this, std::print

Learning Outcomes

After mastering this section, you will:

✅ Write modern, idiomatic C++

  • Use auto for type deduction
  • Apply range-based for loops
  • Leverage structured bindings
  • Use modern container types

✅ Understand modern paradigms

  • Functional programming with lambdas
  • Type constraints with concepts
  • Functional-style ranges
  • Asynchronous code with coroutines

✅ Write safer code

  • Use optional/variant/any
  • Leverage string_view
  • Apply expected for errors
  • Use type-safe formatting

✅ Improve performance

  • Move semantics
  • constexpr evaluation
  • Compile-time computation
  • Parallel algorithms

Code Mapping

Documentation Code Lessons Status
C++11 Features src/03_toolbox/02_modern_features/01_cpp11/ 📝 Planned
C++14 Features src/03_toolbox/02_modern_features/02_cpp14/ 📝 Planned
C++17 Features src/03_toolbox/02_modern_features/03_cpp17/ 📝 Planned
C++20 Features src/03_toolbox/02_modern_features/04_cpp20/ 📝 Planned
C++23 Features src/03_toolbox/02_modern_features/05_cpp23/ 📝 Planned

Modern C++ Quick Reference

Type Deduction

// C++11: auto
auto x = 42;                          // int
auto& y = x;                          // int&
auto&& z = x;                         // int& (forwarding reference)
auto func = []() { return 42; };      // lambda

// C++14: Return type deduction
auto add(int a, int b) {              // return type deduced
    return a + b;
}

// C++17: Class template argument deduction
std::pair p(1, 2.5);                  // std::pair<int, double>
std::vector v{1, 2, 3};               // std::vector<int>
std::tuple t(1, 'a', 3.14);           // std::tuple<int, char, double>

Control Structures

// Range-based for (C++11)
for (const auto& item : container) {
    // Process item
}

// Structured bindings (C++17)
auto [key, value] = map.extract(iterator);
for (const auto& [key, value] : map) {
    // Use key and value directly
}

// if constexpr (C++17)
template<typename T>
auto get_value(T t) {
    if constexpr (std::is_pointer_v<T>) {
        return *t;
    } else {
        return t;
    }
}

Optional and Variant

// std::optional (C++17)
std::optional<int> try_divide(int a, int b) {
    if (b == 0) return std::nullopt;
    return a / b;
}

if (auto result = try_divide(10, 2)) {
    std::cout << *result << "\n";      // Use value
}

// std::variant (C++17)
std::variant<int, float, string> value;
value = 42;
value = 3.14f;
value = "hello";

std::visit([](auto&& arg) {
    std::cout << arg << "\n";
}, value);

String View (C++17)

// Zero-copy string reference
void print(std::string_view str) {
    std::cout << str << "\n";
}

print("hello");                      // No temporary string created
print(std::string("world"));
print(std::string_view(str.data(), 5));

Concepts (C++20)

template<typename T>
concept Sortable = requires(T t) {
    std::sort(t.begin(), t.end());
    { t.size() } -> std::convertible_to<size_t>;
};

template<Sortable T>
void process(T& container) {
    std::sort(container.begin(), container.end());
}

// Or use abbreviated function syntax
void process(Sortable auto& container) {
    std::sort(container.begin(), container.end());
}

Ranges (C++20)

#include <ranges>
#include <vector>

std::vector<int> numbers = {1, 2, 3, 4, 5, 6};

// Functional-style pipelines
auto result = numbers
    | std::views::filter([](int x) { return x % 2 == 0; })
    | std::views::transform([](int x) { return x * 2; })
    | std::views::take(3);

// result = {4, 8, 12}

Three-way Comparison (C++20)

struct Point {
    int x, y;
    auto operator<=>(const Point&) const = default;  // Generate all comparisons
};

Point a{1, 2}, b{1, 3};

if (a < b) { /* ... */ }   // Works
if (a == b) { /* ... */ }  // Also works
if (a >= b) { /* ... */ }  // And this too

Format (C++20/23)

#include <format>

std::string s = std::format("The answer is {}", 42);
std::print("Hello, {}!\n", "World");  // C++23 - no std::cout needed

Modern C++ Idioms

Use auto for readability

// ✅ Good: auto emphasizes semantic meaning
auto container = std::map<int, std::string>{};
auto iterator = container.begin();

// ❌ Bad: Explicit types are verbose
std::map<int, std::string> container;
std::map<int, std::string>::iterator iterator = container.begin();

Prefer range-based for

// ✅ Good: Clean and safe
for (const auto& item : container) {
    process(item);
}

// ❌ Bad: Verbose and error-prone
for (auto it = container.begin(); it != container.end(); ++it) {
    process(*it);
}

Use structured bindings

// ✅ Good: Clear and concise
for (const auto& [key, value] : map) {
    std::cout << key << " = " << value << "\n";
}

// ❌ Bad: Verbose access
for (auto it = map.begin(); it != map.end(); ++it) {
    std::cout << it->first << " = " << it->second << "\n";
}

Progress Tracking

Milestones

  • Use auto effectively
  • Apply range-based for loops
  • Leverage structured bindings
  • Use optional/variant/any appropriately
  • Apply concepts for type constraints
  • Use ranges for functional pipelines
  • Write formatted output with std::format

Previous: 04_stl_mastery/ Next: 06_best_practices/