OOP(Object-Oriented programming) VS. GP(Generic Programming)
- OOP企图将datas 和 methods 关联在一起
数据放在类里面,操作这些数据的函数也放在类里面
template<class T,class Alloc = alloc>
class list{
...
void sort();
}
为什么list不能使用::sort()
排序?
先看标准库sort()源码
template<class RandomAccessIterator>
inline void sort(RandomAccessIterator first,RandomAccessIterator last{
if(first!=last){
__introsort_loop(first,last,value_type(first),__lg(last-first)*2);
__final_insertion_sort(first,last);
}
}
template<class RandomAccessIterator,class T,class Size>
void __introsort_loop(RandomAccessIterator first,Random AccessIterator last,
T*,Size depth_limit){
...
RandomAccessIterator cut = __unguarded_partition(first,last,T(__median(*first,*(first+(last-first)/2,*(last-1))));//只有 RandomAccessIterator 才能如此操作
...
}
RandomAccessIterator相关概念
list链表的数据结构导致它提供的迭代器不符合.因为随机访问迭代器 (RandomAccessIterator) 是能在常数时间内移动到指向任何元素的双向迭代器 (BidirectionalIterator) 。而链表的的访问时线性的,不具有跳跃性.因为它得一个个访问下一个.
GP却是要将datas 和 methods 分开来
- Containers和Algorithms 团队可各自闭门造车,其间以Iterator沟通即可.
- Algorithms通过Iterators 确定操作范围,并通过Iterators取用Containers元素.
template<class T> inline const T& min(const T& a,const T& b){ return b<a?b:a; }
以上面代码为例,函数 min 不需要知道
class T
的细节,T
只要自己实现好<
的操作符重载即可.
tips:所有algorithms,其内最终涉及元素本身的操作,无非就是比大小
template<class T,class Compare>
inline const T& max(const T&a,const T& b,Compare comp){
return comp(a,b)?b:a;
}
bool strLonger(const string& s1,const string& s2){
return s1.size() < s2.size();
}
max(string("zoo"),string("hello"),strLonger);
}
operator overloading
Customizes the C++ operators for operands of user-defined typed.
句法:
Overloaded operators 是具有特殊函数名字的函数
operator op //(1)
operator type //(2)
operator new
operator new[] //(3)
operator delete
operator ddelete[] //(4)
operator "" suffix-identifier //(5) since C++11
/*
1) 重载的运算符;
2) 用户定义的转换函数;
3) 分配函数;
4) 解分配函数;
5) 用户定义字面量。
*/
op - 下列 38 个运算符之一:
+ - * / % ˆ & | ~ ! = < > += -= *= /= %= ˆ= &= |= << >> >>= <<= == != <= >= && || ++ -- , ->* -> ( ) [ ]