【问题标题】:Unable to pipe template class to cout无法通过管道将模板类传递给 cout
【发布时间】:2019-05-22 14:48:22
【问题描述】:

当我尝试编译以下(截断为下面的小sn-p)代码时,

#include <iostream>

using namespace std;

template <typename value_type>
class Tree {
public:
    Tree();
    ~Tree();
};

template <typename value_type>
const std::ostream& operator<<(const std::ostream& o, const Tree<value_type>& t) {
    return o;
}

int main() {
    Tree<int> tree;
    cout << tree << endl;
}

我收到以下错误:

clang 在 Mac 上

error: reference to overloaded function could not be resolved;
      did you mean to call it?
        cout << tree << endl;
                        ^~~~

gnu gcc 在 debian linux 上

error: no match for 'operator<<'
(operand types are
    'const ostream {aka const std::basic_ostream<char>}'
    and '<unresolved overloaded function type>')
        cout << tree << endl;
        ~~~~~~~~~~~~~^~~~~~~

如果我从不实现运算符重载,则 gnu g++ 会给我以下错误:

error: no match for 'operator<<'
(operand types are
    'std::ostream {aka std::basic_ostream<char>}'
    and 'Tree<int>')
        cout << tree << endl;
        ~~~~~^~~~~~~

我实际上不明白我在这里做错了什么。我想做的就是能够像您一样将我的模板类通过管道传输到ostream。有什么想法吗?

【问题讨论】:

    标签: c++ templates compiler-errors ostream c++98


    【解决方案1】:

    删除std::ostream 上的consts - 你不能对任何东西使用 const 流。

    template <typename value_type>
    std::ostream& operator<<(std::ostream& o, const Tree<value_type>& t) {
        return o;
    }
    

    【讨论】:

    • 出于某种原因,我过去曾这样做过,而且效果很好,但现在我的编译器选择只接受非常数..
    • @finnrayment 你可能已经用其他运算符做到了这一点,但我怀疑任何编译器都被破坏到足以让你用operator&lt;&lt;std::ostream 做到这一点。 (请注意,如果您从不使用流,则不会遇到问题 - 只要您的重载不写入任何内容,std::cout &lt;&lt; tree; 就应该可以工作。)
    • 老实说,我发誓我前几天在std::ostream 上用operator&lt;&lt; 完成了它,它在三台以上的计算机上编译...无论如何,你已经解决了我的问题,所以谢谢你非常喜欢!
    • @finnrayment 对于std::cout &lt;&lt; x; 来说“很好”,但除此之外的任何东西都不是。流本身当然不是 const,但 std::cout &lt;&lt; x; 导致 const 引用,因此 std::cout &lt;&lt; x &lt;&lt; whatever; 无法工作
    • @finnrayment 我经常陷入这个陷阱,忘记返回流,忽略警告,在我使用链接之前一切似乎都很好......
    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2020-01-17
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多