I l@ve RuBoard Previous Section Next Section

Item 5. Maximally Reusable Generic Containers桺art 2

Difficulty: 6

Historical note: The example used in this Item is adapted from one presented by Kevlin Henney and later analyzed by Jon Jagger in issues 12 and 20 of the British C++ magazine Overload. (British readers beware: The answer to this Item goes well beyond that presented in Overload #20. In fact, the efficiency optimization presented there won't work in the solution to this problem.)

What is the following solution doing, and why? Explain each constructor and operator. Does this design or code have any flaws?



template<typename T, size_t size> 


class fixed_vector


{


public:


  typedef T*       iterator;


  typedef const T* const_iterator;


  fixed_vector() { }





  template<typename O, size_t osize>


  fixed_vector( const fixed_vector<O,osize>& other )


  {


    copy( other.begin(),


          other.begin()+min(size,osize),


          begin() );


  }





  template<typename O, size_t osize>


  fixed_vector<T,size>&


  operator=( const fixed_vector<O,osize>& other )


  {


    copy( other.begin(),


          other.begin()+min(size,osize),


          begin() );


    return *this;


  }





  iterator       begin()       { return v_; }


  iterator       end()         { return v_+size; }


  const_iterator begin() const { return v_; }


  const_iterator end()   const { return v_+size; }





private:


  T v_[size];


};


    I l@ve RuBoard Previous Section Next Section