名前空間
変種
操作

explicit指定子

From cppreference.com
< cpp‎ | language
 
 
C++言語
全般
フロー制御
条件実行文
if
繰り返し文 (ループ)
for
範囲for (C++11)
ジャンプ文
関数
関数宣言
ラムダ式
inline指定子
動的例外仕様 (C++17まで*)
noexcept指定子 (C++11)
例外
名前空間
指定子
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
記憶域期間指定子
初期化
代替表現
リテラル
ブーリアン - 整数 - 浮動小数点数
文字 - 文字列 - nullptr (C++11)
ユーザー定義 (C++11)
ユーティリティ
属性 (C++11)
typedef宣言
型エイリアス宣言 (C++11)
キャスト
メモリ確保
クラス
クラス固有の関数プロパティ
explicit (C++11)
static

特殊メンバ関数
テンプレート
その他
 
 

目次

[編集] 構文

explicit (1)
explicit ( ) (2) (C++20以降)
- bool 型の文脈的に変換された定数式


1) コンストラクタまたは変換関数(C++11 以降)または推論ガイド(C++17 以降)が explicit であることを指定します。つまり、暗黙の変換コピー初期化には使用できません。
2) explicit 指定子は定数式と共に使用できます。関数は、その定数式がtrueに評価される場合に限り、explicit になります。
(C++20以降)

explicit 指定子は、クラス定義内のコンストラクタまたは変換関数(C++11 以降)の宣言の宣言指定子シーケンス内でのみ現れることができます。

[編集] 備考

関数指定子explicitなしで宣言された単一の非デフォルトパラメータを持つ(C++11 まで)コンストラクタは、変換コンストラクタと呼ばれます。

コンストラクタ(コピー/ムーブ以外)とユーザー定義変換関数の両方が関数テンプレートである場合がありますが、explicitの意味は変わりません。

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

[編集] キーワード

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
}

[編集] 関連項目

English 日本語 中文(简体) 中文(繁體)