explicit指定子
From cppreference.com
目次 |
[編集] 構文
explicit
|
(1) | ||||||||
explicit ( 式 ) |
(2) | (C++20以降) | |||||||
| 式 | - | bool 型の文脈的に変換された定数式 |
|
2) explicit 指定子は定数式と共に使用できます。関数は、その定数式がtrueに評価される場合に限り、explicit になります。
|
(C++20以降) |
explicit 指定子は、クラス定義内のコンストラクタまたは変換関数(C++11 以降)の宣言の宣言指定子シーケンス内でのみ現れることができます。
[編集] 備考
関数指定子explicitなしで宣言された単一の非デフォルトパラメータを持つ(C++11 まで)コンストラクタは、変換コンストラクタと呼ばれます。
コンストラクタ(コピー/ムーブ以外)とユーザー定義変換関数の両方が関数テンプレートである場合がありますが、explicitの意味は変わりません。
|
explicitの後に続く struct S { explicit (S)(const S&); // error in C++20, OK in C++17 explicit (operator int)(); // error in C++20, OK in C++17 }; |
(C++20以降) |
| 機能テストマクロ | 値 | 規格 | 機能 |
|---|---|---|---|
__cpp_conditional_explicit |
201806L |
(C++20) | 条件付きexplicit |
[編集] キーワード
[編集] 例
このコードを実行
struct A { A(int) {} // converting constructor A(int, int) {} // converting constructor (C++11) operator bool() const { return true; } }; struct B { explicit B(int) {} explicit B(int, int) {} explicit operator bool() const { return true; } }; int main() { A a1 = 1; // OK: copy-initialization selects A::A(int) A a2(2); // OK: direct-initialization selects A::A(int) A a3 {4, 5}; // OK: direct-list-initialization selects A::A(int, int) A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int) A a5 = (A)1; // OK: explicit cast performs static_cast if (a1) { } // OK: A::operator bool() bool na1 = a1; // OK: copy-initialization selects A::operator bool() bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization // B b1 = 1; // error: copy-initialization does not consider B::B(int) B b2(2); // OK: direct-initialization selects B::B(int) B b3 {4, 5}; // OK: direct-list-initialization selects B::B(int, int) // B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int, int) B b5 = (B)1; // OK: explicit cast performs static_cast if (b2) { } // OK: B::operator bool() // bool nb1 = b2; // error: copy-initialization does not consider B::operator bool() bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization [](...){}(a4, a5, na1, na2, b5, nb2); // suppresses “unused variable” warnings }