iter_swap example

#include
#include // for iterator_traits
#include // for swap
#include
#include #include

#include
#include

using namespace std;

template struct iter_swap2_impl;

template
void iter_swap2(ForwardIterator1 i1, ForwardIterator2 i2)
{
typedef iterator_traits traits1;
typedef typename traits1::value_type v1;
typedef typename traits1::reference r1;

typedef iterator_traits traits2;
typedef typename traits1::value_type v2;
typedef typename traits1::reference r2;

bool const use_swap =
boost::is_same::value
&& boost::is_reference::value
&& boost::is_reference::value;

iter_swap2_impl::do_it(i1, i2);
}

/*
* Following impl will be called, if
* 1) the value type of two container is the same, and
* 2) operator* returns the true reference of an element in the container.
* (i.e., it doesn’t return proxy reference.)
*/
template<>
struct iter_swap2_impl {
template
static void do_it(ForwardIterator1 i1, ForwardIterator2 i2)
{
cout << "Fast swap" << endl; // Fast, cuz it can swap the reference // itself in the container. swap(*i1, *i2); // std::swap } }; template<>
struct iter_swap2_impl
{
template
static void do_it(ForwardIterator1 i1, ForwardIterator2 i2)
{
cout << "Slow swap" << endl; // Slow, because we always copy things // by value. typename iterator_traits::value_type
tmp = *i1;
tmp = *i2;
*i2 = tmp;
}
};

int main()
{
vector vi;
list li;

vi.push_back(1);
li.push_back(2);

iter_swap2(vi.begin(), li.begin());

cout << "vi: "; copy(vi.begin(), vi.end(), ostream_iterator(cout, ” “));
cout << endl; cout << "li: "; copy(li.begin(), li.end(), ostream_iterator(cout, ” “));
cout << endl; return EXIT_SUCCESS; } [/code] Reference - C++ Template Metaprogramming

Similar Posts:

Post a Comment

Your email is never published nor shared.