Main BLOGGER
Google
WWW THIS BLOG
Wednesday, May 10, 2006
 
c++ wrapper for C array

http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=207&rl=1

 

 

template <class T, int _size> struct array_wrapper
{
 //typedef names used in STL algorithms and containers
 typedef T value_type;
 typedef T* iterator;
 typedef const T * const_iterator;
 typedef T& reference;
 typedef const T& const_reference;
 
T v[_size]; //the actual array
// member functions of STL containers
operator T* () {return v;}
reference operator[] (size_t idx) {return v[idx];}
const_reference operator[] (size_t idx) const {return v[idx];}
 
iterator begin() {return v;}
const_iterator begin() const {return v;}
 
iterator end() {return v+_size;}
const_iterator end() const {return v+_size;}
 
size_t size() const {return _size;}
};

 

 

void func(int *, int sz); // C function 
//wrap an array of 20 int's initializing its members to 0
array_wrapper<int, 20> arr={0}; 
func(arr, arr.size()); //using T* conversion operator

 




<< Home

Powered by Blogger

Google
WWW THIS BLOG