I have overloaded <<
to print the contents of a pair
, in two different forms (see code below). The first form is specific for the pair
type defined. The second is template
d, for any pair. Any of the two is ok for my pair type. When both prototypes precede the definition of main
, the first one (specific) is used, regardless of the order of the prototypes. Only when the prototype for the first is commented, is the second used.
Why is the ambiguity resolved in this way, deciding which is the appropriate function to use?
#include <iostream>
#include <map>
using namespace std;
typedef pair<string, char> pair_t;
ostream& operator<<(ostream& os, const pair_t& p); // First form, specific
template<class first_class, class second_class>
ostream& operator<<(ostream& os, const pair<first_class, second_class>& p); // Second form, generic
int main(void) {
pair_t p2;
p2 = make_pair("Fer", 'C');
cout << p2 << endl;
return 0;
}
ostream& operator<<(ostream& os, const pair_t& p)
{
os << p.first << " obtained \'" << p.second << "\'";
return os;
}
template<class first_class, class second_class>
ostream& operator<<(ostream& os, const pair<first_class, second_class>& p)
{
os << "(" << p.first << ", " << p.second << ")";
return os;
}