Templates 模糊运算符<&书信电报;模板重载

Templates 模糊运算符<&书信电报;模板重载,templates,c++11,operator-overloading,pretty-print,iterable,Templates,C++11,Operator Overloading,Pretty Print,Iterable,下面的代码是我第一次尝试用C++11打印可移植容器。它使用函数模板默认参数功能 #include <ostream> #include <string> #include <utility> template <typename T> void print(std::ostream &o, T const &t) { o<< t; } void print(std::ostream &o, std::stri

下面的代码是我第一次尝试用C++11打印可移植容器。它使用函数模板默认参数功能

#include <ostream>
#include <string>
#include <utility>

template <typename T>
void print(std::ostream &o, T const &t) { o<< t; }

void print(std::ostream &o, std::string const &s){ o<< '"'<< s<< '"'; }

template <typename K, typename V>
void print(std::ostream &o, std::pair<K, V> const &p)
{
  o<< '{'; print(o, p.first);
  o<< ": "; print(o, p.second);
  o<< '}';
}

template <typename C, typename I= typename C::const_iterator>
std::ostream &operator<< (std::ostream &o, C const &c)
{
  o<< '[';
  if(c.empty()) return o<< ']';
  I b= c.begin(), e= c.end(); -- e;
  for(; b!= e; ++ b)
  {
    print(o, *b);
    o<< ", ";
  }
  print(o, *b);
  return o<< ']';
}
#包括
#包括
#包括
模板

void print(std::ostream&o,T const&T){o您可以使用
std::enable_if
在字符串的情况下禁用重载:

template <typename C, typename I= typename C::const_iterator>
typename std::enable_if<!std::is_same<C,std::string>::value,std::ostream>::type &
  operator<< (std::ostream &o, C const &c)
{
  o<< '[';
  if(c.empty()) return o<< ']';
  I b= c.begin(), e= c.end(); -- e;
  for(; b!= e; ++ b)
  {
    print(o, *b);
    o<< ", ";
  }
  print(o, *b);
  return o<< ']';
}
模板
typename std::enable_if::value,std::ostream>::type&

运算符因为
std::string
有一个
常量迭代器
,您的
operator@VaughnCato是的,如果可能的话,我希望std::basic_字符串重载是首选。当
C
是string.OT时,您可以使用
enable_if
禁用重载,但您可以使用
auto b=C.begin()
我想在不启用ifs(因此是默认参数)的情况下执行此操作,而不是
IB
好的调用,但您还是给出了正确的答案。
template <typename C, typename I= typename C::const_iterator>
typename std::enable_if<!std::is_same<C,std::string>::value,std::ostream>::type &
  operator<< (std::ostream &o, C const &c)
{
  o<< '[';
  if(c.empty()) return o<< ']';
  I b= c.begin(), e= c.end(); -- e;
  for(; b!= e; ++ b)
  {
    print(o, *b);
    o<< ", ";
  }
  print(o, *b);
  return o<< ']';
}
template <typename T>
struct is_string : std::false_type {};

template <typename Char,typename Allocator>
struct is_string<std::basic_string<Char,Allocator> > : std::true_type {};

template <typename C, typename I= typename C::const_iterator>
typename std::enable_if<!is_string<C>::value,std::ostream>::type &
  operator<< (std::ostream &o, C const &c)
{
  o<< '[';
  if(c.empty()) return o<< ']';
  I b= c.begin(), e= c.end(); -- e;
  for(; b!= e; ++ b)
  {
    print(o, *b);
    o<< ", ";
  }
  print(o, *b);
  return o<< ']';
}