[英]Would it be possible to overload << operator for a std::map with pair std:string and std::vector<int>?
我之前使用template
為std::map<std::string, int>
重載了std::map
的<<
運算符
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;
}
例如,如果map
是std::map< std::string, std::vector<int> >
,那么如何編寫模板?
有幾種選擇。
首先,您可以為std::vector
提供單獨的operator<<
overload,例如:
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
命名空間是未定義的行為。
看看你目前的方法,我不會重載現有的方法。 我會為這對提供一種新方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.