C++ 运算符使用不明确<&书信电报;在我的课堂上

C++ 运算符使用不明确<&书信电报;在我的课堂上,c++,C++,我在创建运算符时遇到了一个问题您的问题是,您尝试插入的值是无符号的,而您提供的重载仅适用于有符号类型。就编译器而言,将unsigned转换为int或char都同样好/坏,并且会导致歧义。您的问题是,您尝试插入的值是unsigned,而您提供的重载只适用于有符号类型。就编译器而言,将unsigned转换为int或char都同样好/坏,并且会导致歧义 我无法使用模板函数,因为在某些情况下,处理取决于类型 只需对这些类型进行重载 我认为它与我的特定类型(如“Stuff”)之间仍然存在歧义 如果操作员则

我在创建运算符时遇到了一个问题您的问题是,您尝试插入的值是
无符号的
,而您提供的重载仅适用于有符号类型。就编译器而言,将unsigned转换为
int
char
都同样好/坏,并且会导致歧义。

您的问题是,您尝试插入的值是
unsigned
,而您提供的重载只适用于有符号类型。就编译器而言,将unsigned转换为
int
char
都同样好/坏,并且会导致歧义

我无法使用模板函数,因为在某些情况下,处理取决于类型

只需对这些类型进行重载

我认为它与我的特定类型(如“Stuff”)之间仍然存在歧义

如果操作员<代码>则为否 我无法使用模板函数,因为在某些情况下,处理取决于类型

只需对这些类型进行重载

我认为它与我的特定类型(如“Stuff”)之间仍然存在歧义


否。如果
运算符,您实际要解决的问题是什么?也许你最好还是执行一个<代码> STD::SLUBUF或者C++的I/O系统的其他层,而不是整个流。我刚刚意识到了这个问题。doSomething()中的整数是无符号的,并且没有运算符。您实际要解决的问题是什么?也许你最好还是执行一个<代码> STD::SLUBUF或者C++的I/O系统的其他层,而不是整个流。我刚刚意识到了这个问题。doSomething()中的整数是无符号的,没有运算符
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'
}
template <class T>
MyClass& operator<< (const T& t)
{
    m_out << t;
    return *this;
}