Namespaces
Variants

static_assert declaration (since C++11)

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

コンパイル時アサーションのチェックを実行します。

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - HTMLタグ、属性、クラス名はすべて保持されています - リンクテキスト(Syntax、Explanation、Notesなど)はC++関連の専門用語として翻訳せずに保持しています - 番号付けや構造は完全に維持されています

構文

static_assert( ブール定数式 , 未評価文字列 ) (1)
static_assert( ブール定数式 ) (2) (C++17以降)
static_assert( ブール定数式 , 定数式 ) (3) (C++26以降)

静的アサーションを宣言します。アサーションが失敗した場合、プログラムは不適格となり、診断エラーメッセージが生成される可能性があります。

1) 固定エラーメッセージを使用する静的アサーション。
2) エラーメッセージのない静的アサーション。
3) ユーザー定義エラーメッセージ付き静的アサーション。
この構文は、構文 ( 1 ) が一致しない場合にのみ一致します。

説明

bool-constexpr -

コンテキスト的にbool型に変換された定数式 。組み込み変換は許可されないが、 縮小変換 ではない 整数変換 から bool への変換は除く。

(C++23まで)

コンテキスト的に bool に変換される 式で、その変換が 定数式 であるもの

(C++23以降)
unevaluated-string - 評価されない文字列リテラル で、エラーメッセージとして表示されるもの
constant-expression - 定数式 msg で、以下のすべての条件を満たすもの:
  • msg. size ( ) std::size_t に暗黙的に変換可能であること。
  • msg. data ( ) const char * に暗黙的に変換可能であること。

static_assert 宣言は、名前空間スコープおよびブロック スコープ ブロック宣言 として)およびクラス本体内部( メンバー宣言 として)で記述できます。

bool-constexpr が適切に形成され、かつ true と評価される場合、またはテンプレート定義の文脈で評価され、かつテンプレートがインスタンス化されていない場合、この宣言は効果を持ちません。それ以外の場合、コンパイル時エラーが発行され、ユーザーが提供したメッセージ(存在する場合)は診断メッセージに含まれます。

ユーザーが提供したメッセージのテキストは以下のように決定されます:

  • メッセージが unevaluated-string の構文要件に一致する場合、メッセージのテキストは unevaluated-string のテキストとなります。
  • それ以外の場合、以下の値を与える:
メッセージのテキストは、 ptr から始まる len 個の code units のシーケンスによって形成される。これは ordinary literal encoding である。各整数 i について [ 0 , len ) の範囲内で、 ptr [ i ] integral constant expression でなければならない。
(C++26 以降)

注記

標準規格はコンパイラが error message の逐語的なテキストを出力することを要求していませんが、コンパイラは一般に可能な限りそうしています。

エラーメッセージは文字列リテラルでなければならないため、動的な情報や文字列リテラル自体ではない 定数式 を含むことはできません。特に、 名前 テンプレート型引数 を含むことはできません。

(C++26まで)
機能テストマクロ 規格 機能
__cpp_static_assert 200410L (C++11) static_assert (構文 ( 1 ) )
201411L (C++17) 単一引数 static_assert (構文 ( 2 ) )
202306L (C++26) ユーザー生成エラーメッセージ (構文 ( 3 ) )

キーワード

static_assert

#include <format>
#include <type_traits>
static_assert(03301 == 1729); // C++17以降、メッセージ文字列はオプション
template<class T>
void swap(T& a, T& b) noexcept
{
    static_assert(std::is_copy_constructible_v<T>,
                  "Swap requires copying");
    static_assert(std::is_nothrow_copy_constructible_v<T> &&
                  std::is_nothrow_copy_assignable_v<T>,
                  "Swap requires nothrow copy/assign");
    auto c = b;
    b = a;
    a = c;
}
template<class T>
struct data_structure
{
    static_assert(std::is_default_constructible_v<T>,
                  "Data structure requires default-constructible elements");
};
template<class>
constexpr bool dependent_false = false; // CWG2518/P2593R1以前の回避策
template<class T>
struct bad_type
{
    static_assert(dependent_false<T>, "error on instantiation, workaround");
    static_assert(false, "error on instantiation"); // CWG2518/P2593R1によりOK
};
struct no_copy
{
    no_copy(const no_copy&) = delete;
    no_copy() = default;
};
struct no_default
{
    no_default() = delete;
};
#if __cpp_static_assert >= 202306L
// まだ実際のC++ではない(std::formatはconstexprである必要がある):
static_assert(sizeof(int) == 4, std::format("Expected 4, got {}", sizeof(int)));
#endif
int main()
{
    int a, b;
    swap(a, b);
    no_copy nc_a, nc_b;
    swap(nc_a, nc_b); // 1
    [[maybe_unused]] data_structure<int> ds_ok;
    [[maybe_unused]] data_structure<no_default> ds_error; // 2
}

出力例:

1: error: static assertion failed: Swap requires copying
2: error: static assertion failed: Data structure requires default-constructible elements
3: error: static assertion failed: Expected 4, got 2

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
CWG 2039 C++11 変換前の式のみが定数であることが要求される 変換も定数式で有効でなければならない
CWG 2518
( P2593R1 )
C++11 インスタンス化されていない static_assert ( false , "" ) ; は不適格であった 適格となるように変更

参考文献

  • C++23規格 (ISO/IEC 14882:2024):
  • 9.1 前文 [dcl.pre] (p: 10)
  • C++20標準 (ISO/IEC 14882:2020):
  • 9.1 前文 [dcl.pre] (p: 6)
  • C++17 標準 (ISO/IEC 14882:2017):
  • 10 宣言 [dcl.dcl] (p: 6)
  • C++14標準 (ISO/IEC 14882:2014):
  • 7 宣言 [dcl.dcl] (p: 4)
  • C++11標準 (ISO/IEC 14882:2011):
  • 7 宣言 [dcl.dcl] (p: 4)

関連項目

指定されたエラーメッセージを表示し、プログラムを不適格にする
(プリプロセッサディレクティブ)
ユーザー指定の条件が true でない場合、プログラムを異常終了させる。リリースビルドでは無効化される可能性がある。
(関数マクロ)
contract_assert statement (C++26) 実行中の内部条件を検証する
(C++11)
条件付きで関数オーバーロードまたはテンプレート特殊化を オーバーロード解決 から除去する
(クラステンプレート)
Type traits (C++11) 型のプロパティを問い合わせるためのコンパイル時テンプレートベースのインターフェースを定義する
Cドキュメント for Static assertion