我有一個派生basic_ostream類和一個內聯修飾符(類似於setw)。我的流類也應繼承其父級的所有運算符< <行爲。我取決於我是否使用「使用」關鍵字或者沒有得到不同的編譯器錯誤:派生basic_ostream:「使用」關鍵字和運算符模糊過載<<
#include <iostream>
struct modifier { };
template <typename C, typename T=std::char_traits<C> >
struct mystream : public std::basic_ostream<C, T>
{
// this is where the trouble is
using std::basic_ostream<C, T>::operator <<;
inline mystream & operator << (const modifier & mod)
{
// ...custom behavior...
return *this;
}
};
int main()
{
mystream<char> foo;
modifier m;
foo << "string"; // this fails if the using is present
foo << 123; // this fails if the using is absent
foo << m;
}
當我把using指令中,編譯器是混淆了「串」輸出,如果我註釋掉,它會對整數123輸出感到困惑,在這兩種情況下,都會給我「錯誤:'運算符'<'<''的模糊超載。我有g ++ 4.2.1和g ++ 4.8的問題。這裏前進的方向是什麼?
你爲什麼從'basic_ostream'派生?你在做什麼,非會員'運營商''不能做? – 2013-05-03 16:15:50
我在下面評論 - 我的流有很多自定義行爲,包括它自己的streambuf等,並且該運算符需要更改流的狀態。 – 2013-05-03 16:22:02
使用'xalloc'和'iword' /'pword',它們專門用於維護自定義流狀態。如果你想用你自己的'streambuf'('fstream'就是這麼做)來構建一些東西,你就可以從'basic_ostream'派生出來,只是不要添加任何'operator <<'成員給它。 – 2013-05-03 16:29:15