2012-09-27 64 views
0

我有一個類包含std::ofstreamstd::ifstream(一次只能激活一個)。我想超載operator()以返回當前活動流。但std::ofstreamstd::ifstream的常見基類型返回一個通用引用是什麼?公共父類型ifstream和ofstream

+4

'std :: ios',但你真的不能用它做很多事情。 –

+0

[This](http://cplusplus.com/reference/iostream/)和[this](http://en.cppreference.com/w/cpp/io)可能會有所幫助。 – BoBTFish

回答

2

我想超載運算符()返回當前活動流這使得絕對沒有意義和氣味就像設計缺陷。你爲什麼想要回報?那個操作員的調用者應該怎樣處理返回值?它既不能輸入也不能輸出。

我不知道你真正想做的事,但也許這樣的事情可能會爲你工作,但它的危險

template<typename T> class wrapper 
{ 
    T*const ptr; 
    wrapper(T*p) : ptr(p) {} 
public: 
    bool empty() const { return ptr; } 
    operator T&() const 
    { 
    if(empty()) throw some_exception("trying to use empty wrapper"); 
    return *ptr; 
    } 
    friend some_class; 
}; 

class some_class 
{ 
    ifstream _ifstream; 
    ofstream _ofstream; 
    bool ifstream_is_active; 
    bool ofstream_is_active; 
public: 
    operator wrapper<ifstream>() const 
    { wrapper<ifstream>(ifstream_is_active? &_ifstream : 0); } 
    operator wrapper<ofstream>() const 
    { wrapper<ofstream>(ofstream_is_active? &_ofstream : 0); } 
}; 

但這是危險的,因爲你可能處理懸擺指針。你可以通過使用shared_ptr(自己工作)來避免這種情況,但這意味着some_class不再控制這些流的生命週期。

+1

異常規範在C++ 11中被棄用(並且被C++ 03中的一些着名編譯器忽略) - 最好省略它們。此外,您不能僅在返回類型上重載函數。 – ildjarn

+0

@ildjarn你說得很對。我刪除了拋出並糾正了另一個問題(這是一種類型,我打算進行類型轉換) – Walter

1

輸入和輸出流是非常不同的類型。他們共享的唯一通用基類是std::ios。除了一些錯誤檢查的東西,這並沒有多少內容。

這兩種流類型只共享最基本的接口。由於顯而易見的原因,它們彼此之間沒有什麼關係。

+0

我想他想重載他的_own_類的operator()來返回一些流,只是想讓公共基地知道怎麼做返回類型。 – ildjarn

+0

@ildjarn:哦,對。這現在更有意義。 –