なぜ次のコードを書くことができませんか?なぜ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);
私はstd::fstream
さんoperator bool()
がexplicit
として定義されていることを知っているが、私はそれがこのような場合に失敗する理由何らかの理由が表示されません。中間の変換はありません。一時的なstd::ofstream
オブジェクトとbool
です。どういう理由ですか?
演算子は明示的であり、暗黙的にboolに変換するコンテキストがないため、明示的にboolに変換する必要があります。:) –
明示的には、キャストを直接呼び出さない限りboolに変換されません。 –
'return !!'はここで動作します。 –