是否可以为带有 std:string 和 std::vector 的 std::map 重载<<运算符<int>?

Would it be possible to overload << operator for a std::map with pair std:string and std::vector<int>?

本文关键字:lt std 重载 运算符 gt int map vector 是否 string      更新时间:2023-10-16

我之前使用template重载了std::map<<运算符std::map<std::string, int>

template <typename T, typename S> 
std::ostream & operator<<(std::ostream & os, const std::map<T, S>& v) 
{ 
    for (auto it : v)  
        os << it.first << " : " << it.second << "n"; 
    return os; 
} 

例如,如果mapstd::map< std::string, std::vector<int> >,如何编写模板?

有几个选项。

起初,您可以为std::vector提供一个单独的operator<<重载,例如:

template <typename T>
std::ostream& operator<< (std::ostream& s, std::vector<T> const& v)
{ /* your generic implementation */ return s; }

然后,将为地图中的每个向量调用它:

os << it.first << " : " << it.second << "n";
//                           ^ here...

我认为这是最干净的解决方案 - 但如果它太通用并且您只需要针对此特定地图类型进行真正不同的东西,那么您可以专门为这种类型的地图提供单独的重载:

std::ostream& operator<<
        (std::ostream& s, std::map<std::string, std::vector<int>> const& m)
{ /* your specific implementation */ return s; }
或者

,或者,为您的操作员专门负责:

template <>
std::ostream& operator<< <std::string, std::vector<int>>
        (std::ostream& s, std::map<std::string, std::vector<int>> const& m)
{ /* your specific implementation */ return s; }

可能吗?是的,您可以编写代码。

允许吗?否,除非明确指定,否则使用自己的符号扩展 std 命名空间是未定义的行为。

看看你目前的方法,我不会重载现有方法。我会为这对夫妇提供一种新的方法。