在 C++11 中有没有办法让编译器确定函数参数的模板?所以我想为所有类型打印一个只有一个流运算符函数的 C++11 数组,不想为另一种数组类型定义相同的流运算符重载:
ostream& operator<<(ostream& stream, const array<float, 3>& v)
{
stream << v[0] << ", " << v[1] << ", " << v[2];
return stream;
}
我试过这样的:
ostream& operator<<(ostream& stream, const array<auto, 3>& v)
{
stream << v[0] << ", " << v[1] << ", " << v[2];
return stream;
}
或
ostream& operator<<(ostream& stream, const array<typename...>& v)
{
stream << v[0] << ", " << v[1] << ", " << v[2];
return stream;
}
但编译器不会编译这些替代方案。是否有另一个不错的解决方案,或者我真的必须每次都为每种类型定义一个重载函数吗?
最佳答案
您需要一个由数组类型参数化的函数模板:
template <typename T>
ostream& operator<<(ostream& stream, const array<T, 3>& v)
模板参数可以从函数参数推导出来,所以正常使用运算符是可以的:
cout << array<float, 3>{{1,2,3}} << endl;
如果要支持任意数组,大小也可以作为参数
template <typename T, size_t N>
ostream& operator<<(ostream& stream, const array<T, N>& v)
关于c++ - 使用非成员 ostream 重载函数打印任何 c++11 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28631962/