0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】C++20でよく使われる機能

0
Posted at

C++20でよく使われる機能

C++20 は C++11 以来の大規模なアップデートです。特に Concepts、Ranges、Modules、Coroutines が代表的な新機能で、std::span、std::format、std::jthreadなども利用頻度が高い機能です。

よく使われる機能

機能 概要
Concepts テンプレートの型に制約を付ける
Ranges / Views 範囲の検索や変換・フィルタリングを記述
std::span 連続したメモリ領域を非所有で参照
std::format 型安全な書式付き文字列を生成
三方比較演算子 <=> 比較演算の定義を簡潔にする
std::jthread スレッド終了時のjoinと停止要求をサポート
consteval コンパイル時計算を強制
constinit 静的・スレッド記憶域の変数で定数初期化を強制
std::source_location 呼び出し元のファイル名や行番号を取得
contains mapなどでキーの存在を確認
starts_with / ends_with 文字列の前方・後方一致を調べる
指示付き初期化子 .x = 10のように集成体を初期化

言語機能の追加・改善

機能 概要
Concepts / requires テンプレートの制約を明示
Modules ヘッダーと異なる仕組みでインターフェースを分割
Coroutines 関数の実行を中断・再開
<=> 三方比較によって比較処理を定義
consteval 即時関数を定義
constinit 定数初期化を保証
指示付き初期化子 集成体のメンバ名を指定
[[likely]] / [[unlikely]] 分岐の確率に関する最適化ヒント
char8_t UTF-8コード単位を表現する型
非型テンプレート引数の拡張 一定の構造体などをテンプレート引数に使う

標準ライブラリの追加・改善

機能 概要
std::ranges 範囲対応アルゴリズム
std::span ポインタと要素数をまとめたビュー
std::format 書式付き文字列
std::jthread join可能なRAIIスレッド
std::stop_token 協調的キャンセル
std::counting_semaphore セマフォ
std::latch / std::barrier スレッド同期
std::atomic_ref 既存のオブジェクトに対するアトミック操作
std::bit_cast ビット表現を保持する型変換
std::endian エンディアンを表す列挙型
std::source_location 呼び出し元の位置情報
std::numbers piなどの数学定数
std::midpoint 整数のオーバーフロー等を考慮した中間値
std::to_array 配列からstd::arrayを生成
std::erase / std::erase_if コンテナ要素の削除
std::chronoの拡張 カレンダー・タイムゾーンなど

よく使うC++20のコード例

Concepts

#include <concepts>

template<std::integral T>
T Add(T a, T b) { return a + b; }

int result = Add(10, 20);
// Add(1.0f, 2.0f); // 型制約を満たさない

Ranges

#include <ranges>
#include <vector>

std::vector<int> values = {1, 2, 3, 4, 5, 6};
auto even = values | std::views::filter([](int x) { return x % 2 == 0; });
for (int x : even) {
    // 2, 4, 6
}

viewsは一般に遅延評価であり、元のコンテナの寿命や変更に注意します。

std::span

#include <span>
#include <vector>

void Process(std::span<const float> data) {
    for (float x : data) { /* ... */ }
}

float a[] = {1.0f, 2.0f};
std::vector<float> b = {3.0f, 4.0f};
Process(a);
Process(b);

std::format

#include <format>
#include <string>

std::string text = std::format("HP={}, Speed={:.2f}", 100, 3.14159f);

三方比較演算子

#include <compare>

struct Version {
    int major;
    int minor;
    auto operator<=>(const Version&) const = default;
};

bool older = Version{1, 0} < Version{2, 0};
bool equal = Version{1, 0} == Version{1, 0};

std::jthreadと停止要求

#include <thread>

void Worker(std::stop_token token) {
    while (!token.stop_requested()) {
        // 定期的に停止要求を確認する処理
    }
}

void Start() {
    std::jthread t(Worker);
    // スコープの終端で停止要求後にjoinされる
}

停止要求は強制終了ではありません。ワーカー側がstop_tokenを確認する必要があります。

consteval

consteval int Square(int n) { return n * n; }
constexpr int result = Square(10);

指示付き初期化子

struct Position { float x, y, z; };
Position p{.x = 10.0f, .y = 20.0f, .z = 30.0f};

C++の指示付き初期化子は集成体に使用し、メンバの宣言順で指定します。

std::source_location

#include <source_location>
#include <iostream>

void Log(std::source_location where = std::source_location::current()) {
    std::cout << where.file_name() << ':' << where.line() << '\n';
}

void Update() { Log(); }

C++17との比較

項目 C++17 C++20
テンプレートの型制約 enable_ifなど Concepts
コレクション操作 STLアルゴリズム Ranges / Views
連続メモリのビュー ポインタ+長さなど std::span
書式付き文字列 printfやストリームなど std::format
スレッド管理 std::thread std::jthread
比較演算子 個別に実装 <=>
コード分割 従来型ヘッダー Modules
中断・再開 独自実装など Coroutines

学習の流れ

  1. std::span
  2. Conceptsとrequires
  3. Ranges / Views
  4. std::format
  5. std::jthread / std::stop_token
  6. consteval / constinit
  7. std::source_location
  8. std::bit_cast / std::endian
  9. Modules
  10. Coroutines

参考

https://en.cppreference.com/w/cpp/20

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?