名前空間
変種
操作

static_assert

提供: cppreference.com
< cpp‎ | language
 
 
C++言語
一般的なトピック
フロー制御
条件付き実行文
繰り返し文 (ループ)
ジャンプ文
関数
関数宣言
ラムダ関数宣言
inline 指定子
例外指定 (C++20未満)
noexcept 指定子 (C++11)
例外
名前空間
指定子
decltype (C++11)
auto (C++11)
alignas (C++11)
記憶域期間指定子
初期化
代替表現
リテラル
ブーリアン - 整数 - 浮動小数点
文字 - 文字列 - nullptr (C++11)
ユーザ定義 (C++11)
ユーティリティ
属性 (C++11)
typedef 宣言
型エイリアス宣言 (C++11)
キャスト
暗黙の変換 - 明示的な変換
static_cast - dynamic_cast
const_cast - reinterpret_cast
メモリ確保
クラス
クラス固有の関数特性
特別なメンバ関数
テンプレート
その他
 
 

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

目次

[編集] 構文

static_assert ( bool_constexpr , message ) (C++11以上)
static_assert ( bool_constexpr ) (C++17以上)

[編集] 説明

bool_constexpr - 文脈的に変換された bool 型の定数式
message - bool_constexpr が false の場合にコンパイルエラーとして現れるオプショナルな (C++17以上)文字列リテラル。

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

bool_constexprtrue を返す場合は、この宣言は効果がありません。 そうでなければ、コンパイル時エラーが発行され、その診断メッセージに message のテキスト (もしあれば) が含まれます。

message は省略できます。

(C++17以上)

[編集] ノート

message は文字列リテラルでなければならないため、動的な情報や、たとえ定数式であってもそれが文字列リテラルでなければ、含めることはできません。 特に、テンプレートの型引数名前を含めることはできません。

[編集] 欠陥報告

以下の動作変更欠陥報告は以前に発行された C++ 標準に遡って適用されました。

DR 適用先 発行時の動作 正しい動作
CWG 2039 C++11 only the expression before conversion is required to be constant the conversion must also be valid in a constant expression

[編集]

#include <type_traits>
 
template <class T>
void swap(T& a, T& b)
{
    static_assert(std::is_copy_constructible<T>::value,
                  "Swap requires copying");
    static_assert(std::is_nothrow_copy_constructible<T>::value
               && std::is_nothrow_copy_assignable<T>::value,
                  "Swap requires nothrow copy/assign");
    auto c = b;
    b = a;
    a = c;
}
 
template <class T>
struct data_structure
{
    static_assert(std::is_default_constructible<T>::value,
                  "Data Structure requires default-constructible elements");
};
 
struct no_copy
{
    no_copy ( const no_copy& ) = delete;
    no_copy () = default;
};
 
struct no_default
{
    no_default () = delete;
};
 
int main()
{
    int a, b;
    swap(a, b);
 
    no_copy nc_a, nc_b;
    swap(nc_a, nc_b); // 1
 
    data_structure<int> ds_ok;
    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

[編集] 関連項目

static_assertC言語リファレンス