C ++流插入重载错误

时间:2017-09-09 21:11:05

标签: c++ operator-overloading

我遇到基本流插入过载问题。代码相当不言自明:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>
#include <string>

class dictionary
{
public:
  using map_type = std::map<std::string, std::string>;
  using ostream_iterator_type = std::ostream_iterator<map_type::value_type>;

private:
  map_type inner;

public:
  dictionary() : inner()
  {
    inner["foo"] = "lorem";
    inner["baz"] = "ipsum";
  }

  void
  write(std::ostream& os)
  {
    os << "{\n";
    std::copy(std::begin(inner), std::end(inner), ostream_iterator_type(os, "\n"));
    os << "}";
  }
};

dictionary::ostream_iterator_type::ostream_type&
operator<<(dictionary::ostream_iterator_type::ostream_type& os,
           dictionary::map_type::value_type const& p)
{
  os << p.first << " => " << p.second;
  return os;
}

此代码抛出一些巨大的模板错误,声称operator<<没有适当的重载,我已经明确定义了两个参数。我错过了什么明显的问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

我注意到的第一件事是缺少<ostream><algorithm>。此外,您似乎只在需要后才定义operator <<。但真正的问题是,您尝试将operator <<定义为::std::pair作为std命名空间之外的第二个参数。您可以按照以下方式正确地重新定义它:

#include <iterator>
#include <map>
#include <string>
#include <ostream>
#include <algorithm>

class dictionary
{
public:
  using map_type = std::map<std::string, std::string>;

private:
  map_type inner;

public:
  dictionary() : inner()
  {
    inner["foo"] = "lorem";
    inner["baz"] = "ipsum";
  }

  void
  write(std::ostream& os);
};

namespace std
{
  std::ostream &
  operator <<(std::ostream & os, dictionary::map_type::const_reference & p)
  {
    os << p.first << " => " << p.second;
    return os;
  }
} // namespace std

void dictionary::
write(std::ostream& os)
{
  using ostream_iterator_type = std::ostream_iterator<map_type::value_type>;
  os << "{\n";
  std::copy(std::begin(inner), std::end(inner), ostream_iterator_type(os, "\n"));
  os << "}";
}