Files
Obsidian-Main/20. 專注/C++/C++20.md

2.2 KiB

Modules

Modules provide a new way to organize and manage large codebases, helping to improve build times, reduce code duplication, and increase modularity.

// Example: math.cppm  
export module math;  
  
export int square(int x) {  
  return x * x;  
}  
  
export int cube(int x) {  
  return x * x * x;  
}  
  
// Example: main.cpp  
import math;  
  
int main() {  
  int result = math::square(5);  
  // result = 25  
  int result2 = math::cube(5);  
  // result2 = 125  
}

Concepts

Concepts provide a way to specify constraints on templates, making it easier to write generic code that works with a wide range of types.

template <typename T>  
concept Addable = requires(T a, T b) {  
  { a + b } -> T;  
};  
  
template <Addable T>  
T add(T a, T b) {  
  return a + b;  
}  
  
int main() {  
  int x = 1, y = 2;  
  auto result = add(x, y);  
  // result = 3  
}

Ranges

Ranges provide a new way to manipulate sequences of data in C++, making it easier to write clean, readable, and efficient code.

#include <ranges>  
#include <iostream>  
  
int main() {  
  std::vector<int> v{1, 2, 3, 4, 5};  
  auto even = v | std::ranges::views::filter([](int x) { return x % 2 == 0; });  
  for (int x : even) {  
    std::cout << x << '\n';  
  }  
}

Contract Programming

Contract programming allows developers to specify preconditionspostconditions, and assertions in their code, making it easier to catch bugs early and reduce the number of runtime errors.

#include <iostream>  
  
[[nodiscard]] int foo() {  
  return 42;  
}  
  
int main() {  
  int x = foo();  
  std::cout << x << '\n';  
}

Improved Template Metaprogramming

C++20 includes several imrovements to the way templates can be used in C++, making it easier to write generic code that can be used with a wide range of types.

#include <type_traits>  
  
template <typename T>  
struct is_integral : std::false_type {};  
  
template <>  
struct is_integral<int> : std::true_type {};  
  
int main() {  
    static_assert(is_integral<int>::value, "");  
    static_assert(!is_integral<float>::value, "");  
}