无法通过管道将模板 class 传递给 cout
Unable to pipe template class to cout
当我尝试编译以下(截断为下面的小片段)代码时,
#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;
~~~~~^~~~~~~
我真的不明白我在这里做错了什么。我想要做的就是能够像您一样将我的模板 class 传送到 ostream
。有什么想法吗?
删除 std::ostream
上的 const
- 您不能将 const 流用于任何事情。
template <typename value_type>
std::ostream& operator<<(std::ostream& o, const Tree<value_type>& t) {
return o;
}
当我尝试编译以下(截断为下面的小片段)代码时,
#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;
~~~~~^~~~~~~
我真的不明白我在这里做错了什么。我想要做的就是能够像您一样将我的模板 class 传送到 ostream
。有什么想法吗?
删除 std::ostream
上的 const
- 您不能将 const 流用于任何事情。
template <typename value_type>
std::ostream& operator<<(std::ostream& o, const Tree<value_type>& t) {
return o;
}