The following code from C++ Primer Plus creates a simple Pair template
#include <iostream>
#include <string>
template <class T1, class T2>
class Pair {
private:
T1 a;
T2 b;
public:
T1 & first();
T2 & second();
T1 first() const { return a; }
T2 second() const { return b; }
Pair(const T1 & aval, const T2 & bval) : a(aval), b(bval) { }
Pair() {}
};
template<class T1, class T2>
T1 & Pair<T1,T2>::first() { return a; }
template<class T1, class T2>
T2 & Pair<T1,T2>::second() { return b; }
What bothers me is how the first() and second() methods work, or better yet, why there's 2 different implementations, one returning a reference to a class T1/2 and the other returning a copy.
I do understand what's the difference between passing reference and passing a copy, but how am I supposed to access one method or the other?
Example:
Pair myPair(5,10);
cout << myPair.first();
which method is going to be called? The one that returns a T1 reference or the one that returns a copy? And how can I call the "other version" of first()?