使用C++中的模板类为容器类型重载'opeator <<'

aan*_*nrv 1 c++ templates operator-overloading

我试图做的:

template <class T>
ostream& operator<<(ostream& ou, map<T,T> x) {
    for(typename map<T,T>::iterator it = x.begin(); it != x.end(); it++) {
        ou << it->first << ": " << it->second << endl;
    }
    return ou;
}
Run Code Online (Sandbox Code Playgroud)

我在主要测试它:

int main() {
    map<char, int> m;
    m['a']++;
    m['b']++;
    m['c']++;
    m['d']++;

    cout << m << endl;
}
Run Code Online (Sandbox Code Playgroud)

然后我得到了错误:

'错误:'std :: cout << m'中'operator <<'不匹配

如果我将函数参数更改为map<T,T>to,则重载的运算符将起作用map<char,int>.我的代码中是否存在小问题,或者有完全不同的方法吗?一般来说,如何使用模板类重载容器类型的运算符?

jua*_*nza 8

您的运算符仅适用于键类型和映射类型相同的映射(例如std::map<int,int>std::map<char,char>.

您需要两个模板参数:

template <class K, class V>
std::ostream& operator<<(std::ostream& ou, const map<K,V>& x) { .... }
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,没有理由复制map,所以我修改了运算符以取代const引用.