Getting ready

It is recommended that you read the recipe Using range-based for loops to iterate on a range before continuing with this one if you need to understand how range-based for loops work and what is the code the compiler generates for such a loop.

To show how we can enable range-based for loops for custom types representing sequences, we will use the following implementation of a simple array:

    template <typename T, size_t const Size> 
class dummy_array
{
T data[Size] = {};

public:
T const & GetAt(size_t const index) const
{
if (index < Size) return data[index];
throw std::out_of_range("index out of range");
}

void SetAt(size_t const index, T const & value)
{
if (index < Size) data[index] = value;
else throw std::out_of_range("index out of range");
}

size_t GetSize() const { return Size; }
};

The purpose of this recipe is to enable writing code like the following:

    dummy_array<int, 3> arr; 
arr.SetAt(0, 1);
arr.SetAt(1, 2);
arr.SetAt(2, 3);

for(auto&& e : arr)
{
std::cout << e << std::endl;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset