Boost学习笔记 operators

如果一个类要实现operator<,operator+,意味着可能也要实现operator>, operator+=,等其它操作符。只要提供了operator<,operator+=就可以根据这两个操作符实现operator>,operator+=
等其它操作符。而且这种实现是单调的
operator >(const T& x, const T& y) { return y < x; }
所以boost提供了这些实现,只要提供了最基本的操作符,那些重复的劳动就不用自己去做了
 
首先要看一下CRTP模式
―――――――――――――――――――――――――――――――――――――――
The Curiously Recurring Template Pattern(CRTP)。这个模式本身是指将派生类作为参数在它自己的模板化基类里使用
―――――――――――――――――――――――――――――――――――――――
template <typename D>
class B
{
 
   template<typename U>
   friend
   D operator+= (D & d, const U & other)
   {
      d = d + other;
      return d;
   }
};
 
 
class D: private B<D>
{
public :
   template<typename U>
   D operator + (const U& other)
   {
        return D(b_ + other);
   }
  
   D operator + (const D& other)
   {
        return D(b_ + other.b_);
   }
 
   explicit D(int b):b_(b)
   {
   }
  
   D():b_(0){};
 
   void print()
   {
        cout<<b_<<endl;
   }
 
private :
     int b_;
};
 
int main()
{
   D d(10);
   D e;
 
   e += 5;
   e.print();
 
   e += d;
   e.print();
}
上面通过提供运用CRTP模式来实现了operator += 操作,你只要提供operator+操作,那么就可以自动帮助你实现operator +=操作。基类中
   template<typename U>
   friend
   D operator+= (D & d, const U & other)
这是基类的友元函数,而不是成员函数,如果是成员函数,那么派生类就不能私有继承基类(那样operator +=)就变的不可访问。
通过CRTP,可以将和派生类类型相关的相同操作都提取到一个基类中
template <typename D>
struct B
{
 size_t size()
 {
      return sizeof(D);
 }
 
   void printType()
 {
      cout<<typeid(D).name()<<endl;
 }
};
 
class D:public B<D>
{
};
Boost 的operators库提供了完整的比较操作符,算术操作符,迭代器操作符
下面是个例子
――――――――――――――――――――――――――――――――――――――――――――――
class thing :
 boost::less_than_comparable<thing>,
 boost::equivalent<thing> {
 
 std::string name_;
public :
 thing() {}
 explicit thing(const std::string& name):name_(name) {}
 
 friend bool operator<(const thing& lhs,const thing& rhs) {
    return lhs.name_<rhs.name_;
 }
};
它提供了以下这些操作符
bool operator<(const thing&,const thing&);
bool operator>(const thing&,const thing&);
bool operator<=(const thing&,const thing&);
bool operator>=(const thing&,const thing&);
bool operator==(const thing&,const thing&);
――――――――――――――――――――――――――――――――――――――
此外boost的operators库还提供了很多其它的基类
less_than_comparable,equality_comparable,addable,subtractable等等,在使用它们的时候都要求遵循一定的语义,比如说使用ess_than_comparable的时候要求必须提供
bool operator<(const T&, const T&); 
语义
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值