operator << must take exactly one argument

前端 未结 4 2079
一个人的身影
一个人的身影 2020-12-04 12:06

a.h

#include \"logic.h\"
...

class A
{
friend ostream& operator<<(ostream&, A&);
...
};

logic.cpp

#inclu         


        
4条回答
  •  渐次进展
    2020-12-04 12:24

    I ran into this problem with templated classes. Here's a more general solution I had to use:

    template class 
    class myClass
    {
        int myField;
    
        // Helper function accessing my fields
        void toString(std::ostream&) const;
    
        // Friend means operator<< can use private variables
        // It needs to be declared as a template, but T is taken
        template 
        friend std::ostream& operator<<(std::ostream&, const myClass &);
    }
    
    // Operator is a non-member and global, so it's not myClass::operator<<()
    // Because of how C++ implements templates the function must be
    // fully declared in the header for the linker to resolve it :(
    template 
    std::ostream& operator<<(std::ostream& os, const myClass & obj)
    {
      obj.toString(os);
      return os;
    }
    

    Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.

    The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(

    Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.

    This works too:

    template class 
    class myClass
    {
        int myField;
    
        // Helper function accessing my fields
        void toString(std::ostream&) const;
    
        // For some reason this requires using T, and not U as above
        friend std::ostream& operator<<(std::ostream&, const myClass &)
        {
            obj.toString(os);
            return os;
        }
    }
    

    I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.

提交回复
热议问题