Nevermind, I figured it out by checking
Code:
std::cout << (typeid(std::map<int, double>::value_type) == typeid(std::pair<int, double>)) << '\n';
and
std::cout << (typeid(std::map<int, double>::value_type) == typeid(std::pair<const int, double>)) << '\n';
The specialization didn't match because the map's key_type is const.
---------------------
Just for the fun, here's a class to help print standard containers' contents.
Code:
#include <iostream>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <limits>
template <class Container, class ValueType = typename Container::value_type >
struct Printer
{
void print(std::ostream& os, typename Container::const_iterator it) const
{
os << *it;
}
};
template <class Container>
struct Printer <Container, std::pair<const typename Container::key_type, typename Container::mapped_type> >
{
void print(std::ostream& os, typename Container::const_iterator it) const
{
os << it->first << '=' << it->second;
}
};
template <class Container>
class Repr
{
const Container& c;
Printer<Container> printer;
const std::string separator;
typename Container::size_type max;
public:
Repr(const Container& c, const std::string& sep, typename Container::size_type n): c(c), separator(sep), max(n) {}
template <class C>
friend std::ostream& operator << (std::ostream& os, const Repr<C>& cont);
};
template <class Container>
std::ostream& operator << (std::ostream& os, const Repr<Container>& cont)
{
if (cont.max == 0 || cont.c.begin() == cont.c.end()) {
return os;
}
typename Container::size_type counter = 1;
typename Container::const_iterator it = cont.c.begin();
cont.printer.print(os, it);
for (++it; it != cont.c.end() && counter != cont.max; ++it, ++counter) {
os << cont.separator;
cont.printer.print(os, it);
}
if (it != cont.c.end()) {
os << cont.separator << "...";
}
return os;
}
template <class Container>
Repr<Container> make_repr(
const Container& c,
const std::string& separator = std::string(" "),
typename Container::size_type max = std::numeric_limits<typename Container::size_type>::max()
)
{
return Repr<Container>(c, separator, max);
}
int main()
{
std::string data[] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven" };
typedef std::list<std::string> Container;
Container array(data, data + sizeof(data) / sizeof(data[0]));
std::cout << make_repr(array) << '\n' //print using defaults
<< make_repr(array, ", ", 4) << '\n' //print first 4 items, using user-defined delimiter
<< make_repr(array, "\n") << '\n'; //print each item on a new line
std::map<std::string, int> Map;
Map["One"] = 1;
Map["Two"] = 2;
Map["Three"] = 3;
Map["Four"] = 4;
std::cout << make_repr(Map, ", ") << '\n'; //works for std::map too
}