怎么重载operator << for C中的数组?

我试着这样做:
template <typename T>
ostream &operator<<(ostream &os,T &arr)
{ /*...*/ }

但是T代表一个数组吗?重载<<<<<<<数组的运算符? 编辑: 根据Kerrek SB的建议,这是我对<<的实现

template <typename T,unsigned int N>
ostream &operator<<(ostream &os,const T (&arr)[N])
{
    int i;
    for(i = 0; i < N; i++)
        os << arr[i] << " ";
    os << endl;
    return os;
}

我的实施是对的吗?我收到了编译错误.

解决方法

你可以这样做:
template <typename T,unsigned int N>
std::ostream & operator<<(std::ostream & os,const T (&arr)[N])
{
  // ..
  return os;
}

当然,这仅适用于编译时数组.请注意,当T是内置类型或std命名空间中的类型时,不允许您实例化此模板!

如果可能的话,可能最好使这个内联,因为你将为每个N引起一个单独的实例化.(pretty printer一个例子.)

但是,您会注意到毯子模板引入了歧义,因为os<< “Hello”现在有两个可能的重载:模板匹配const char(&)[6],以及衰减到指针const char *的(非模板)重载,它们都具有相同的转换序列.我们可以通过禁用char数组的重载来解决这个问题:

#include <ostream>
#include <type_traits>

template <typename T,unsigned int N>
typename std::enable_if<!std::is_same<T,char>::value,std::ostream &>::type
operator<<(std::ostream & os,const T (&arr)[N])
{
  // ..
  return os;
}

实际上,为了更加通用,您还可以制作basic_ostream参数模板参数:

template <typename T,unsigned int N,typename CTy,typename CTr>
typename std::enable_if<!std::is_same<T,std::basic_ostream<CTy,CTr> &>::type
operator<<(std::basic_ostream<CTy,CTr> & os,const T (&arr)[N])
{
  // ..
  return os;
}

鉴于T必须是用户定义的类型,您甚至可以替换is_same< T,char>与is_fundamental< T>进行更多检查(但用户仍然不得将此用于标准库类型的数组).

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...