Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2003-01-11 14:07:39


On Saturday, January 11, 2003, at 01:17 PM, David B. Held wrote:

> "Howard Hinnant" <hinnant_at_[hidden]> wrote in message
> news:332C005E-2585-11D7-9E76-003065D18932_at_twcny.rr.com...
>> [...]
>> Despite the fact that I suggested it, I don't find it a killer
>> example.
>> ;-)
>>
>> I already code stuff like this, with this other pattern:
>> [...]
>
> The fact that the concept is familiar to you already works in its
> favor,
> just as the familiarity of "Hello, world" is its primary feature. It
> provides an entry point for people not necessarily exposed to
> metaprogramming. Just seeing PTS spelled as "mpl::if_" might
> produce an "Aha!" in people checking out MPL, just like Hello,
> World does for a new language.

Well then here's a little toy container that switches between
heap-based and stack-based depending upon the fixed size length. Maybe
has enough guts to spark interest, but not so much that it is too big
to take in at a glance?

template <class T, unsigned int N>
class stack_based
{
protected:
     static unsigned int const size = N;

     T data_[N];

     stack_based() {}
private:
     stack_based(const stack_based& x);
};

template <class T, unsigned int N>
class heap_based
{
protected:
     static unsigned int const size = N;

     T* data_;

     heap_based() : data_(new T[size]){}
     ~heap_based() {delete [] data_;}
     heap_based& operator=(const heap_based& x)
         {std::copy(x.data_, x.data_ + size, data_); return *this;}
private:
     heap_based(const heap_based& x);
};

template <class T, unsigned int N = 10>
class MyContainer
     : private if_<N <= 10, stack_based<T, N>, heap_based<T, N> >::type
{
     typedef typename if_<N <= 10, stack_based<T, N>, heap_based<T, N>
>::type base;
public:
     using base::size;

     // construct
     MyContainer() {}
     MyContainer(const MyContainer& x)
         {std::copy(x.data_, x.data_ + size, base::data_);}

     T& operator[](unsigned int i) {return base::data_[i];}
     const T& operator[](unsigned int i) const {return base::data_[i];}

     typedef T* iterator;
     typedef const T* const_iterator;

     iterator begin() {return base::data_;}
     iterator end() {return base::data_ + size;}
     const_iterator begin() const {return base::data_;}
     const_iterator end() const {return base::data_ + size;}
};

-Howard


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk