我在創建運算符< <在這種特殊情況下的課程中遇到問題。我有一個包裝std :: ostream的類,所以我可以在傳遞給ostream之前對某些類型或某些條件進行一些預處理,並且想要直接傳遞一些東西。我不想繼承std :: ostream,除非我有一個好的論點。 (我想我嘗試了一次,發現很困難,但沒有成功。)模糊使用運算符<<在我的課堂內
我不能使用模板函數,因爲在某些情況下處理取決於類型,我認爲模糊會保留在它和那些對於我的具體類型(如'Stuff')。我必須訴諸使用typeid?
class MyClass
{
private:
std::ostream & m_out;
public:
MyClass (std::ostream & out)
: m_out(out)
{}
MyClass & operator<< (const Stuff & stuff)
{
//...
// something derived from processing stuff, unknown to stuff
m_out << something;
return *this;
}
// if I explicitly create operator<< for char, int, and double,
// such as shown for char and int below, I get a compile error:
// ambiguous overload for 'operator<<' on later attempt to use them.
MyClass & operator<< (char c)
{
m_out << c; // needs to be as a char
return *this;
}
MyClass & operator<< (int i)
{
if (/* some condition */)
i *= 3;
m_out << i; // needs to be as an integer
return *this;
}
// ...and other overloads that do not create an ambiguity issue...
// MyClass & operator<< (const std::string & str)
// MyClass & operator<< (const char * str)
};
void doSomething()
{
MyClass proc(std::cout);
Stuff s1, s2;
unsigned i = 1;
proc << s1 << "using stuff and strings is fine" << s2;
proc << i; // compile error here: ambiguous overload for 'operator<<' in 'proc << i'
}
你實際上試圖解決什麼問題?也許你最好實施一個'std :: streambuf'或者C++ I/O系統的其他層而不是整個流? – 2013-05-01 13:07:01
我剛剛意識到了這個問題。 doSomething()中的整數是無符號的,並且沒有運算符<<(無符號)。當然,由於沒有完全匹配,編譯器不知道使用哪一個......我希望我不必重寫所有簽名/未簽名類型的變體。 – ozzylee 2013-05-01 13:07:04