在这种特殊情况下,我在类中创建 operator<< 时遇到问题。我有一个包装 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'
}