使用具体输出操作符的声明(带有具体签名)

using declaration for concrete output operator (with concrete signature)

本文关键字:输出 操作符 声明      更新时间:2023-10-16
namespace nm
{
  class C1 {};
  class C2 {};
  inline std::ostream& operator << (std::ostream& lhs, std::vector<C1> const&) { return lhs; }
  inline std::ostream& operator << (std::ostream& lhs, std::vector<C2> const&) { return lhs; }
}
using nm::operator<<;

是否有办法声明在全局命名空间nm中只使用operators <<中的一个,而不是两个?

一种解决方案是将每个operator<<放在自己的嵌套名称空间中:

namespace nm
{
  class C1 {};
  class C2 {};
  namespace nm1 {
    inline std::ostream& operator << (std::ostream& lhs, C1 const&) { return lhs; }
  }
  namespace nm2 {
    inline std::ostream& operator << (std::ostream& lhs, C2 const&) { return lhs; }
  }
}
using nm::nm1::operator<<;

现场演示