J Woltman J Woltman - 4 months ago 41
C++ Question

Is it Possible to Use Casting as "array slicing" in C++11

I have some shared memory populated by specialized hardware. It's declared as an array of structs, like

int bus[10]port[5]data[10]
. I'm (re)learning C++, and wanted to use C++11's ranged for loops to iterate over the data.

HOWEVER: That last dimension of the array (
), I only care about the first 4 elements. Is there a way to take a slice of the data and use it in the for() statement?


for (auto & b : bus) {
for (auto & p : bus.port) {
for (auto & d : port.data[0 through 3]) {

Is there a way to use a cast in the innermost for loop, so that it appears like there's only 4 elements? The address of the data is important because I'm going to refer directly to it later using pointers.


This is probably one of those times when a good old-fashioned for (int i = 0; i < 4; i++) is your best bet.

Don't overthink it, and don't try to use "new" features just for the sake of it, creating more complexity and more work in the process.