I'm getting a compile error for the following code, which tries to overload cout to print a hashmap<string, vector<string>>. Because map iterators give pairs, I created an overload for the pair class. However, when compiling, the pair object attempts to use the generic one over the specific one. I read that the compiler tries to find the most specific one...
#include <unordered_map>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template<typename T , template<typename...>class C , typename... Z , typename = enable_if_t<!is_same_v<C<T , Z...> , string>>>
ostream& operator<<(ostream& os , const C<T , Z...>& c) {
os << '{';
if (c.size()) {
os << *c.begin();
for (auto it = ++c.begin();it != c.end();++it)
os << ", " << flush << *it;
}
return os << '}';
}
template<typename T , typename U>ostream& operator<<(ostream& os , const pair<T , U>& p) {
return os << '(' << p.first << ", " << p.second << ')';
}
int main() {
unordered_map<string , vector<string>> graph;
graph["a"].push_back("b");
graph["b"].push_back("a");
cout << graph << endl;
}
Here is a snippet of my error:
10 | if (c.size()) {
| ~~^~~~
.\z.cpp:11:18: error: 'const struct std::pair<const std::__cxx11::basic_string<char>, std::vector<std::__cxx11::basic_string<char> > >' has no member named 'begin'
11 | os << *c.begin();
| ~~^~~~~
