Wednesday 26 November 2008

C++: An STL-like circular buffer (Part 9)

Here's a little extra method we can easily add: back(). In a similar way to std::vector, std::deque, and std::list, the circular_buffer can support a back method, which returns a reference to the item at the end of the container.

Remember, m_back refers to the next unused item, so if we have anything in the buffer, it will be stored in the previous element.
// In declaration
reference back();
const_reference back() const;

template <typename T, typename A>
inline
typename circular_buffer<T,A>::reference circular_buffer<T,A>::back()
{
assert(m_front);
return *wrap(m_back-1);
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::const_reference circular_buffer<T,A>::back() const
{
assert(m_front);
return *wrap(m_back-1);
}

No comments: