在这种特殊情况下,我在类中创建operator <
我不能使用模板函数,因为在某些情况下,处理取决于类型,并且我认为它与我的特定类型(如“ Material ”)之间仍然存在歧义。我必须使用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'
}

最佳答案

您的问题是,您尝试插入的值是unsigned,而您提供的重载仅适用于带符号的类型。就编译器而言,将unsigned转换为intchar都是好/坏,而且会造成歧义。

关于c++ - 在类中含糊不清的使用operator <<,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16318633/

10-09 18:32