我正在尝试这样做:
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;
}
我的实现是否正确?我遇到了编译错误。
Foo<T>
。那么你可以只为这些数组重载:template <typename T, int N> ... (..., const Foo<T> (&arr)[N])
。这样就不会与字符串字面值发生冲突了。 - Kerrek SBspdlog
一起使用,因为它消耗了这些流操作符。一个快速而不太优雅的解决方法是明确地使用stringstream。 - Steven Lu