[英]Why can I use `operator<<` on temporary std::ofstream objects?
[英]Why can't I use operator bool() for std::ofstream
為什么我不能編寫以下代碼?
#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
。 什么原因?
正是因為 operator bool()
被定義為explicit
,所以您不能以這種方式使用它。 其中一個唯一的上下文explicit operator bool()
被自動調用是明確的條件語句,比如if
while
, ?:
, !
和for
的中間表達式。 (有關更完整的摘要,請參見我的問題。 何時可以在不進行operator bool
情況下使用顯式operator bool
? )。
return
語句的值永遠不會在上下文中轉換為bool
,因此,如果要將std::ofstream
轉換為bool
作為返回值,則必須使用static_cast<bool>()
或等效值。
由於運算符像顯式一樣聲明,並且沒有上下文允許隱式轉換為bool(例如,在if語句中使用),因此您必須將包含流的表達式顯式轉換為bool
。 例如
bool touch(const std::string& file_path)
{
return bool( std::ofstream(file_path, std::ios_base::app) );
}
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>
轉換(最好是static_cast<bool>
),因為隱式轉換很危險。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.