模板的引入 使c++產生了泛型的算法 泛型的容器
這兩個是個好東西 但是在將兩項技術結合的時候產生了一個問題 就是在寫程序的時候要暴露對象的類型
就像這個樣子 :
template<typename T>
vector<T>::iterator find(const T& )
{
........
}
而如果暴露了類型的話 那么就不能寫一段代碼而完成問題了 必須為每種容器都寫出相同的算法
怎么辦呢 可以在find中傳出兩個參數
template<typename T>
vector<T>::iterator find(const T&, T& result )
{
........
}
但是好像還是有問題 譬如類型的引用 還有size 指針 等等 都是不同的類型 寫起來還是很頭大
于是 聰明的人們想出了type traits這項技術
這項技術
typename<typename T>
class iterator
{
public:
typedef T value_type
}
typename<typename I>
typename I::value_type
find(I &)
{
}
與STL的實現不同 在boost中 他們使用的是模板片特化來實現的type traits
基本思想就是 默認大部分都不支持某種特性 然后 當某個類型支持時就為他特化一個類 支持這樣的特性
感覺這樣寫的話 在特化的時候會不會代碼會比較多呢 ...
具體就是
template<typename T>
class something
{
// 在這里寫對廣大的類的操作
}
然后對于特殊的類型 譬如說 int
template<>
class something<int>
{
//然后在這里寫對Int做的特殊的操作
}
而為了type traits來說 它的特殊操作就是在泛型類里面做一個枚舉 值為false而在 int里面這個值為true
那么 當算法來用這個對象時 可以根據這個枚舉的值來選擇相應的算法 ,譬如對int的速度比較快的 或者對泛型的正確的算法
下面是 std::swap的一個優化版本
//
// iter_swap:
// tests whether iterator is a proxying iterator or not, and
// uses optimal form accordingly:
//
namespace detail{
template <typename I>
static void do_swap(I one, I two, const boost::false_type&)
{
typedef typename std::iterator_traits<I>::value_type v_t;
v_t v = *one;
*one = *two;
*two = v;
}
template <typename I>
static void do_swap(I one, I two, const boost::true_type&)
{
using std::swap;
swap(*one, *two);
}
}
template <typename I1, typename I2>
inline void iter_swap(I1 one, I2 two)
{
//
// See is both arguments are non-proxying iterators,
// and if both iterator the same type:
//
typedef typename std::iterator_traits<I1>::reference r1_t;
typedef typename std::iterator_traits<I2>::reference r2_t;
typedef boost::integral_constant<bool,
::boost::is_reference<r1_t>::value
&& ::boost::is_reference<r2_t>::value
&& ::boost::is_same<r1_t, r2_t>::value> truth_type;
detail::do_swap(one, two, truth_type());
}
其中 boost::integral_constant<bool, ::boost::is_reference<r1_t>::value
&& ::boost::is_reference<r2_t>::value
&& ::boost::is_same<r1_t, r2_t>::value> truth_type
就是一個枚舉 看傳入的參數是否可以用std::swap 如果可以則連接到std::swap不然就用自己寫的 呵呵