0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++: explicit とは

Last updated at Posted at 2025-12-19

初めに

この記事のコードをChatGPTに読ませたら、

explicit Proxy(Json& r) : ref(r) {}

という文が追加されていた。

explicitとは

概要

クラスや構造体に対して、暗黙的な型変換を禁止するキーワード。

コンストラクタに指定する場合と、型変換演算子に指定する場合がある。

コンストラクタ

コンストラクタにexplicitを指定したクラスは以下の制約が課される。

  1. コピー初期化の禁止
  2. 暗黙的な型変換の禁止
class Hoge{
    explicit Hoge(int) {};
}

void hoge(Hoge hoge){}

int main(){
    Hoge h1(0);//OK
    Hoge h2 = 1;//Error: コピー初期化
    Hoge h3 = Hoge(2);//OK

    hoge(h1);//OK
    hoge(0);//Error: 暗黙的な型変換
    hoge(Hoge(2));//OK
    return 0;
}

型変換演算子

型変換演算子についても同様に、暗黙的な型変換を禁止する。

class Piyo{
explicit operator bool() {
    return 0;
}
};
int main(){
    Piyo p;
    
    if(p)//Error
    if(static_cast<bool>(p))//OK
}

Proxyに追加する理由

ProxyJsonを操作するためのクラスであり、Jsonから暗黙的に生成されるべきでない。

かららしい。
つまりProxyの生成箇所をoperator[]に限定するため。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?