An answer recently posted on Stack Overflow showed code that provides, to a standard algorithm, a comparator taking operands of different types:
2. Use a comparator with templated
operator()
.Instead of using a lambda, define a functor with a templated
operator()
.struct comparator { template<typename T, typename U> bool operator()(T const& lhs, U const& rhs) const { return lhs.mCommonField < rhs.mCommonField; } };
Then, it's as easy as:
std::sort(aStructs.begin(), aStructs.end(), comparator{}); std::sort(bStructs.begin(), bStructs.end(), comparator{}); // ... std::set_intersection(aStructs.begin(), aStructs.end(), bStructs.begin(), bStructs.end(), std::back_inserter(intersection), comparator{} );
Just note that as there is a template in the comparator, it must be declared outside of function scope. Live example on Coliru Viewer.
Apparently this at least works in practice, as evidenced by the working live demo.
But is it strictly allowed by the standard?