无法将模板类传递给cout

时间:2019-05-22 14:48:23

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

当我尝试编译以下代码(在下面的小片段中截断)时,

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

我收到以下错误:

在Mac上

clang

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。有什么想法吗?

1 个答案:

答案 0 :(得分:6)

删除const上的std::ostream-您不能将const流用于任何内容。

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