近来学习C++11,对其中的move语意比较着迷,顺手写了一个swap类。
这个类用来交换2个同类型对象(类型为T)的值,配合我博客前面的type_traits的类可以萃取T的特性,然后用最效率办法做交换(尽量使用move语意)
特点:
1.如果T类型有默认构造函数,使用T的默认构造函数来生成MySwap对象,否则使用T的拷贝构造函数。
2.如果T类型有move语意的=操作符,使用move语意的=操作符实现A和B的值交换,否则使用普通的=操作符。
3.针对类型T可以做type_traits的模板特化来实现特性设置。
用法:
1. MySwap<T> myswap(A); //A的类型为T
2. myswap.swap(A, B); // A和B的类型为T
#ifndef MySwap_H_
#define MySwap_H_
#include <utility>
#include "type_traits.h"
template<typename T>
inline void _swap(T& lhs, T& rhs, T& temp, SGISTL::false_type)
{
temp = lhs;
lhs = rhs;
rhs = temp;
}
template<typename T>
inline void _swap(T& lhs, T& rhs, T& temp, SGISTL::true_type)
{
temp = std::move(lhs);
lhs = std::move(rhs);
rhs = std::move(temp);
}
template<typename T, typename ConstructType = typename type_traits<T>::has_trivial_default_constructor>
class MySwap
{
private:
T Data_;
public:
typedef T value_type;
typedef typename type_traits<T>::has_trivial_default_constructor construct_type;
typedef typename type_traits<T>::has_move_assigment_operator assigment_type;
public:
explicit MySwap(const T &t):Data_(t)
{
}
void swap(T& lhs, T& rhs)
{
_swap(lhs, rhs, this->Data_, assigment_type());
}
private:
MySwap(const MySwap &rhs);
MySwap& operator = (const MySwap&);
bool operator == (const MySwap&);
};
template<typename T>
class MySwap<typename T, SGISTL::true_type>
{
private:
T Data_;
public:
typedef T value_type;
typedef SGISTL::true_type construct_type;
typedef typename type_traits<T>::has_move_assigment_operator assigment_type;
public:
explicit MySwap(const T&):Data_()
{
}
void swap(T& lhs, T& rhs)
{
_swap(lhs, rhs, this->Data_, assigment_type());
}
private:
MySwap(const MySwap &rhs);
MySwap& operator = (const MySwap &);
bool operator == (const MySwap&);
};
#endif