| Home | Libraries | People | FAQ | More

### An improved Version of std::iter_swap

Demonstrates a version of `std::iter_swap` that use type traits to determine whether an it's arguments are proxy iterators or not, if they're not then it just does a `std::swap` of it's dereferenced arguments (the same as `std::iter_swap` does), however if they are proxy iterators then takes special care over the swap to ensure that the algorithm works correctly for both proxy iterators, and even iterators of different types (see iter_swap_example.cpp):

    //
    // iter_swap:
    // tests whether iterator is a proxy iterator or not, and
    // uses optimal form accordingly:
    //
    namespace detail{

    template <typename I>
    static void do_swap(I one, I two, const boost::false_type&)
    {
       typedef typename std::iterator_traits<I>::value_type v_t;
       v_t v = *one;
       *one = *two;
       *two = v;
    }
    template <typename I>
    static void do_swap(I one, I two, const boost::true_type&)
    {
       using std::swap;
       swap(*one, *two);
    }

    }

    template <typename I1, typename I2>
    inline void iter_swap(I1 one, I2 two)
    {
       //
       // See is both arguments are non-proxying iterators,
       // and if both iterator the same type:
       //
       typedef typename std::iterator_traits<I1>::reference r1_t;
       typedef typename std::iterator_traits<I2>::reference r2_t;

       typedef boost::integral_constant<bool,
          ::boost::is_reference<r1_t>::value
          && ::boost::is_reference<r2_t>::value
          && ::boost::is_same<r1_t, r2_t>::value> truth_type;

       detail::do_swap(one, two, truth_type());
    }