John Bartholomew John Bartholomew - 1 month ago 10
C++ Question

Can iter_swap be specialised?

If I have a container

std::vector<T*> items
, I can create an
IndirectIterator
which wraps
std::vector<T*>::iterator
and allows iterating over
T
's rather than
T*
's.

Can I specialise
iter_swap
for
IndirectIterator
to make standard algorithms (such as
std::sort
) swap items by pointer?

i.e., if I write the following, will it have any effect on standard algorithms?

namespace some_namespace
{
template <typename IterT>
class IndirectIterator
{
IterT m_base;
public:
typedef IterT base_iterator;
typedef /* ... */ reference;

/* ... */

reference operator*() const { **m_base; }

const base_iterator& base() const { return m_base; }
base_iterator& base() { return m_base; }
};

template <typename T>
void iter_swap(IndirectIterator<T>& a, IndirectIterator<T>& b)
{
using std::iter_swap;
iter_swap(a.base(), b.base());
}
}


The benefit of this specialisation is that it swaps pointers rather than full T instances, so it's faster (potentially).

Answer

As far as I can see, iter_swap is only used in std::reverse, and it does not mention any kind of argument-dependent lookup: it always uses std::iter_swap. And since you are not allowed to overload functions in the std namespace, you're out of luck.