Can I use the [] operator in C++ to create virtual arrays
- by Shane MacLaughlin
I have a large code base, originally C ported to C++ many years ago, that is operating on a number of large arrays of spatial data. These arrays contain structs representing point and triangle entities that represent surface models. I need to refactor the code such that the specific way these entities are stored internally varies for specific scenarios. For example if the points lie on a regular flat grid, I don't need to store the X and Y coordinates, as they can be calculated on the fly, as can the triangles. Similarly, I want to take advantage of out of core tools such as STXXL for storage. The simplest way of doing this is replacing array access with put and get type functions, e.g.
point[i].x = XV;
becomes
Point p = GetPoint(i);
p.x = XV;
PutPoint(i,p);
As you can imagine, this is a very tedious refactor on a large code base, prone to all sorts of errors en route. What I'd like to do is write a class that mimics the array by overloading the [] operator. As the arrays already live on the heap, and move around with reallocs, the code already assumes that references into the array such as
point *p = point + i;
may not be used. Is this class feasible to write? For example writing the methods below in terms of the [] operator;
void MyClass::PutPoint(int Index, Point p)
{
if (m_StorageStrategy == RegularGrid)
{
int xoffs,yoffs;
ComputeGridFromIndex(Index,xoffs,yoffs);
StoreGridPoint(xoffs,yoffs,p.z);
} else
m_PointArray[Index] = p;
}
}
Point MyClass::GetPoint(int Index)
{
if (m_StorageStrategy == RegularGrid)
{
int xoffs,yoffs;
ComputeGridFromIndex(Index,xoffs,yoffs);
return GetGridPoint(xoffs,yoffs); // GetGridPoint returns Point
} else
return m_PointArray[Index];
}
}
My concern is that all the array classes I've seen tend to pass by reference, whereas I think I'll have to pass structs by value. I think it should work put other than performance, can anyone see any major pitfalls with this approach. n.b. the reason I have to pass by value is to get
point[a].z = point[b].z + point[c].z
to work correctly where the underlying storage type varies.