I work a lot with pairs of values: std::pair<int, int> my_pair
. Sometimes I need to perform the same operation on both my_pair.first
and my_pair.second
.
My code would be much smoother if I could do my_pair[j]
and loop over j=0,1.
(I am avoiding using arrays because I don't want to bother with allocating memory, and I use pair
extensively with other things).
Thus, I would like to define operator[]
for std::pair<int, int>
.
And I can't get it to work, (I'm not very good with templates and such)...
#include <utility>
#include <stdlib.h>
template <class T1> T1& std::pair<T1, T1>::operator[](const uint &indx) const
{
if (indx == 0)
return first;
else
return second;
};
int main()
{
// ....
return 0;
}
fails to compile. Other variations fail as well.
As far as I can tell, I am following the Stack Overflow operator overloading FAQ, but I guess I am missing something...