【问题标题】:ambiguous overload with ostreamostream 的模棱两可的重载
【发布时间】:2022-01-28 11:55:13
【问题描述】:

我不知道为什么要在 c++ 中重叠 std::array 的 ostream。 (错误:'operator

#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;
}

【问题讨论】:

  • 错误指向&lt;&lt; "\n" 部分。我猜你需要#include &lt;iostream&gt;
  • 我试过了,但是没用
  • 你提供了operator&lt;&lt;,它可以接受任何东西。这使得 operator&lt;&lt; 的所有标准库重载都模棱两可
  • 感谢您的回复
  • 我们有什么替代措施来解决这个问题吗?

标签: c++ c++17


【解决方案1】:

这会强制重载仅采用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2012-12-08
    相关资源
    最近更新 更多