重载运算符<<用于数组,无需类

Overloading operator<< for array without the need of a class

本文关键字:lt 用于 运算符 重载 数组      更新时间:2023-10-16

我有一个问题。在C 中,我可以超载operator<<,以便我可以打印一个给定尺寸的数组,而无需课程吗?我设法打印了一个数组,但前提

是的,绝对可以做到。

继续定义该操作员的过载以采用您想要的任何东西。它不需要类型。

所以,类似的东西:

template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
   for (const auto& el : arr)
      os << el << ' ';
   return os;
}

(实时演示(

但是,我警告不要对此过分;其他使用您的代码的程序员可能不会期望它,而且没有其他没有类型的非类型类型(考虑所有整数,char类型,bool和Pointers和Pointers已经"做某事"流式传输时(。


完整的演示代码,用于后续:

#include <iostream>
#include <cstddef>
template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
   for (const auto& el : arr)
      os << el << ' ';
   return os;
}
int main()
{
    int array[] = {6,2,8,9,2};
    std::cout << array << 'n';
}
// Output: 6 2 8 9 2

另一种做到这一点的方法是用std::copystd::ostream_iterator

#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstddef>
template <typename T, auto N>
auto& operator<<(std::ostream& os, T(&arr)[N])
{
  std::copy(std::cbegin(arr), std::cend(arr), std::ostream_iterator<T>(os, " "));
  return os;
}
int main()
{
    int array[] = { 6, 2, 8, 9, 2};
    std::cout << array << 'n';
}
// Output: 6 2 8 9 2