C++11__自己实现的一个swap类

近来学习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


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值