boost::less_than_comparable

来源:互联网 发布:win10软件不兼容 编辑:程序博客网 时间:2024/05/29 19:59

在实际的编程过程中,我们有时候需要对自定义的类重载操作运算符,以便可以进行类之间的比较等操作。

此时,我们可能就需要重载所需的运算符。 但是重载一个类型的操作符时,保证所有操作符都有重载是一件乏味并容易出错的工作,并且确存在这样的事实:其中一些重载的运算符函数可以通过某个或几个的重载运算符函数得出。

举个例子来说:当我们需要重载>、<、>=和<=操作符的时候。如果我们重载了<运算符,那么其实我们通过<就能够确认其他等式。

幸运的是,在Boost.Operators中就提供了这种便捷的方法。通过使用Boost.Operators我们能减少不必要的工作量并且能确保其正确性。

boost库中通过把大多数运算符封装到基类中,使用时你只需在自定义类中继承它,并实现所要求的重载操作符,那么我们的自定义类(即派生类)中就有了所需的所有操作符的实现了。

这里我们就以boost::less_than_comparable为例来说明。

下面是boost::less_than_comparable的源码实现:

template <class T, class U, class B = operators_detail::empty_base<T> >struct less_than_comparable2 : B{     friend bool operator<=(const T& x, const U& y) { return !static_cast<bool>(x > y); }     friend bool operator>=(const T& x, const U& y) { return !static_cast<bool>(x < y); }     friend bool operator>(const U& x, const T& y)  { return y < x; }     friend bool operator<(const U& x, const T& y)  { return y > x; }     friend bool operator<=(const U& x, const T& y) { return !static_cast<bool>(y < x); }     friend bool operator>=(const U& x, const T& y) { return !static_cast<bool>(y > x); }};template <class T, class B = operators_detail::empty_base<T> >struct less_than_comparable1 : B{     friend bool operator>(const T& x, const T& y)  { return y < x; }     friend bool operator<=(const T& x, const T& y) { return !static_cast<bool>(y < x); }     friend bool operator>=(const T& x, const T& y) { return !static_cast<bool>(x < y); }};
上面的less_than_comparable2需要提供>和<,下面的less_than_comparable1只需要提供<即可。

我们来看一个例子:

#ifndef __DISTANCE_H__#define __DISTANCE_H__#include <boost/operators.hpp>class CDistance : public boost::less_than_comparable<CDistance>{public:friend bool operator<(const CDistance &lDistance, const CDistance &rDistance);CDistance(int iDistance):m_iDistance(iDistance){}~CDistance() { }private:int m_iDistance;};bool operator<(const CDistance &lDistance, const CDistance &rDistance){return lDistance.m_iDistance < rDistance.m_iDistance;}#endif//#ifndef __DISTANCE_H__
#include <iostream>#include "Distance.h"using namespace std;int main(void){CDistance distance1(10);CDistance distance2(10);if (distance1 >= distance2){cout << "distance1 >= distance2" << endl;}else{cout << "distance1 < distance2" << endl;}return 0;}
输出结果如下:

distance1 >= distance2
可以见通过Boost.Operators能帮助我们正确的重载大部分的运算符。

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 我爱她她不爱我怎么办 孩子爱发脾气·父母怎么办 落枕怎么办简单快速的有效方法 老板评奖时偏把我落下怎么办 手机home键坏了怎么办 庙里求的葫芦丢了怎么办 判了抚养费不给怎么办 百度账号密码忘了怎么办 百度云会员到期后文件怎么办 百度网盘存储空间不足怎么办 网赌一天输14万怎么办 在部队训练伤了怎么办 cdrx6激活时不能继续了怎么办 大学毕业一年后找不到工作怎么办 农村乱收垃圾费怎么办 信用卡额度低不想要怎么办 qq公告有敏感词怎么办 qq群公告敏感词怎么办 轿车加了假汽油怎么办? 电信4g变成3g怎么办 电信流量超过40g怎么办 联通卡网络信号很差怎么办 电马桶马达坏了怎么办 我这么好看别人看不到怎么办 户口打回原籍不接受怎么办 小电充电宝丢失怎么办 qq连续聊天断了怎么办 胚胎怀疑在切口处怎么办 3D渲染没有材质怎么办 员工拒绝签收员工手册怎么办 二级密码错了三次怎么办 棉签掉到耳朵里怎么办 发财树叶子有黄斑怎么办 翠兰的颈枯萎了怎么办 翠兰主干软了怎么办 花叶子长白色粘粉末怎么办 水培转土培栀子花叶子蔫了怎么办 水冷空调水不循环怎么办 哺乳期乳房一个大一个小怎么办 我喝酒后喂奶了怎么办 磁盘目录不具有读写权限怎么办