static_assert
提供: cppreference.com
コンパイル時アサーションチェックを行います。
目次 |
[編集] 構文
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_constexpr が true を返す場合は、この宣言は効果がありません。 そうでなければ、コンパイル時エラーが発行され、その診断メッセージに 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 |
[編集] 例
Run this code
#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_assert の C言語リファレンス
|