template <typename T,typename U>
std::pair<T,U> operator+(const std::pair<T,U> & l,const std::pair<T,U> & r) {
return {l.first+r.first,l.second+r.second};
}
int main ()
{
std::pair<int, int> a=std::make_pair(1,2);
std::pair<int, int> b=std::make_pair(3,3);
std::pair<int, int> c = a+b;
return 0;
}
You can also do this with more template types to support adding two different types. Right now it supports adding pairs where the first and second are different types, but the two pairs and the return must have the same type.
If you want to make the function really versatile you could do this
template <typename T,typename U, typename V,typename W>
auto operator+(const std::pair<T,U> & l,const std::pair<V,W> & r)
-> std::pair<decltype(l.first+r.first),decltype(l.second+r.second)>
{
return {l.first+r.first,l.second+r.second};
}
In c++14 you might be able to get away with auto instead of the trailing return type, if you explicitly return a pair.