overloading friend operator<< for template class

后端 未结 5 768
误落风尘
误落风尘 2020-11-22 01:34

I have read couple of the questions regarding my problem on StackOverflow.com now, and none of it seems to solve my problem. Or I maybe have done it wrong... The overloaded

5条回答
  •  孤街浪徒
    2020-11-22 02:21

    I think you shouldn't make friend in the first place.

    You can create a public method call print, something like this (for a non template class):

    std::ostream& MyClass::print(std::ostream& os) const
    {
      os << "Private One" << privateOne_ << endl;
      os << "Private Two" << privateTwo_ << endl;
      os.flush();
      return os;
    }
    

    and then, outside the class (but in the same namespace)

    std::ostream& operator<<(std::ostream& os, const MyClass& myClass)
    {
      return myClass.print(os);
    }
    

    I think it should work also for template class, but I haven't tested yet.

提交回复
热议问题