Here's a use case. Suppose you have a compile-time-sized buffer class:
Code:
template <typename E, size_t Size>
class buffer;
Suppose further you want this buffer to be in the class if it is smaller than some threshold, but dynamically allocated if it's larger. (That's because the primary use for the buffer is to be on the stack, but space is limited.)
Code:
const size_t THRESHOLD = 1024 * 16; // 16k
Here's one way to do it at zero runtime cost.
Code:
#include <stddef>
#include <boost/scoped_array.hpp>
#include <boost/mpl/if.hpp>
using std::size_t;
namespace detail
{
template <typename E, size_t Size>
class direct_holder
{
E m_data[Size];
public:
E *ptr() { return m_data; }
E const *ptr() const { return m_data; }
};
template <typename E, size_t Size>
class heap_holder
{
boost::scoped_array<E> m_data;
public:
heap_holder() : m_data(new E[Size]) {}
E *ptr() { return m_data.get(); }
E const *ptr() const { return m_data.get(); }
};
}
template <typename E, size_t Size>
class buffer :
private boost::mpl::if_c<
Size < THRESHOLD,
direct_holder<E, Size>,
heap_holder<E, Size>
>::type
{
// Don't forget to use this->ptr()
};
Of course, if memory serves, that's exactly the strategy pattern, but with automatic strategy selection.