ostream 的模糊重载
ambiguous overload with ostream
我一直坚持为什么要在 C++ 中重叠 std::array 的 ostream。
(错误:'operator<<' 的不明确重载(操作数类型是 'std::ostream' {aka 'std::basic_ostream'} 和 'const char [2]')
这是我的脚本:
#include <bits/stdc++.h>
using namespace std;
template<typename T>
ostream& operator <<(ostream& out, T& arr)
{
bool pre = false;
for(auto& i : arr)
{
if(pre) out << ' ';
pre = true;
out << i;
}
return out;
}
signed main()
{
array<int, 4> a = {123, 123, 12, 12};
cout << a << "\n";
return 0;
}
这会强制重载仅占用 std::array
,这应该可以解决您的模棱两可的重载问题:
template<typename T, std::size_t N>
ostream& operator <<(ostream& out, const std::array<T, N> &arr)
{
bool pre = false;
for(auto& i : arr)
{
if(pre) out << ' ';
pre = true;
out << i;
}
return out;
}
我一直坚持为什么要在 C++ 中重叠 std::array 的 ostream。 (错误:'operator<<' 的不明确重载(操作数类型是 'std::ostream' {aka 'std::basic_ostream'} 和 'const char [2]') 这是我的脚本:
#include <bits/stdc++.h>
using namespace std;
template<typename T>
ostream& operator <<(ostream& out, T& arr)
{
bool pre = false;
for(auto& i : arr)
{
if(pre) out << ' ';
pre = true;
out << i;
}
return out;
}
signed main()
{
array<int, 4> a = {123, 123, 12, 12};
cout << a << "\n";
return 0;
}
这会强制重载仅占用 std::array
,这应该可以解决您的模棱两可的重载问题:
template<typename T, std::size_t N>
ostream& operator <<(ostream& out, const std::array<T, N> &arr)
{
bool pre = false;
for(auto& i : arr)
{
if(pre) out << ' ';
pre = true;
out << i;
}
return out;
}