2016-09-02 12 views
6

なぜ次のコードを書くことができませんか?なぜstd :: ofstreamに演算子bool()を使用できないのですか

#include <fstream> 
#include <string> 

bool touch(const std::string& file_path) 
{ 
    return std::ofstream(file_path, std::ios_base::app); 
} 

int main() 
{ 
    touch("foo.txt"); 
} 

出力

prog.cpp: In function 'bool touch(const string&)': 
prog.cpp:6:52: error: cannot convert 'std::ofstream {aka std::basic_ofstream<char>}' to 'bool' in return 
    return std::ofstream(file_path, std::ios_base::app); 

http://ideone.com/IhaRaD

私はstd::fstreamさんoperator bool()explicitとして定義されていることを知っているが、私はそれがこのような場合に失敗する理由何らかの理由が表示されません。中間の変換はありません。一時的なstd::ofstreamオブジェクトとboolです。どういう理由ですか?

+0

演算子は明示的であり、暗黙的にboolに変換するコンテキストがないため、明示的にboolに変換する必要があります。:) –

+0

明示的には、キャストを直接呼び出さない限りboolに変換されません。 –

+1

'return !!'はここで動作します。 –

答えて

11

それはoperator bool()がこのように使用できないと定義されているためです。正確にはです。 explicit operator bool()が自動的に呼び出される唯一のコンテキストは、if()while(),?:、中間の式for()などの明確な条件のためです。あなたは戻り値としてBOOLするstd::ofstreamを変換したい場合は

、あなたはstatic_cast<bool>()または同等のものを使用する必要があります。

3

演算子は明示的に宣言されており、暗黙的にboolに変換するコンテキストはありません(たとえばifステートメントで使用する場合など)。ストリームを含む式を明示的にboolに変換する必要があります。 例

bool touch(const std::string& file_path) 
{ 
    return bool(std::ofstream(file_path, std::ios_base::app)); 
} 
0

についてoperator boolの定義は次のようになります。

explicit operator bool() {/*...*/} 

注ここで明示的に使用、これはブール値のクラスからの自動キャストがないことを意味します。それはあなたのコード手段と、あなたはこれを行う必要がありません:

#include <fstream> 
#include <string> 

bool touch(const std::string& file_path) 
{ 
    return static_cast<bool>(std::ofstream(file_path, std::ios_base::app)); 
} 

int main() 
{ 
    touch("foo.txt"); 
} 

をどんなにキャストが必要とされるもの、(好ましくはstatic_cast<bool>)、理由は暗黙の型変換が危険であることの。

関連する問題