【发布时间】:2012-03-17 23:11:01
【问题描述】:
以下代码有效,但我想将 ostream& operator
#include<iostream>
#include<map>
using namespace std;
template <class T>
class hash {
private:
map<string, T> _map;
public:
T& operator[] (string x);
friend ostream& operator<<(ostream& out, const hash<T> &rhs) { return out << "test"; }
};
template <class T>
T & hash<T>::operator[](string x) {
return _map[x];
}
int main () {
hash<int> myobject;
myobject["a"] = 1;
cout << myobject["a"] << endl;
cout << myobject << endl;
return 0;
}
我试过了:
template <class T>
ostream& operator<<(...) {
return out << "test";
}
和
ostream& operator<<(...) {
return out << "test";
}
以及其他一些组合都无济于事。
【问题讨论】:
-
见this
-
overloading friend operator<< for template class 的可能重复项(我写了一个描述性很强的答案,其中包含您可能想要查看的不同选项 there)。
标签: c++ templates generics friend