97 lines
2.2 KiB
Markdown
97 lines
2.2 KiB
Markdown
## Modules
|
||
|
||
Modules provide a new way to organize and manage large codebases, helping to improve build times, reduce code duplication, and increase modularity.
|
||
```cpp
|
||
// 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.
|
||
```cpp
|
||
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.
|
||
```cpp
|
||
#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 **_preconditions_**, **_postconditions_**, and **_assertions_** in their code, making it easier to **catch** bugs early and reduce the number of runtime errors.
|
||
```cpp
|
||
#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.
|
||
|
||
```cpp
|
||
#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, "");
|
||
}
|
||
``` |