Невозможно передать шаблонный класс в cout - PullRequest
3 голосов
/ 22 мая 2019

Когда я пытаюсь скомпилировать следующий (урезанный в небольшой фрагмент ниже) код,

#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

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 Ответ

6 голосов
/ 22 мая 2019

Удалите const s на std::ostream - вы не можете использовать поток const ни для чего.

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