I have two overloads of a member function:
const std::vector<Tile*>& Level::calculateTilesWithinAABB(const gm::AABB& Box)
{
static std::vector<Tile*> Tiles;
Tiles.clear();
/* Calculations to add pointers to elements
in member std::vector<Tile> to Tiles: */
auto Pos = pxToGridPos(Box.getTopLeft());
auto Top = pxToGridPos(Box.getTop());
auto Right = pxToGridPos(Box.getRight());
auto Bottom = pxToGridPos(Box.getBottom());
for (; Pos.x <= Right; ++Pos.x)
for (Pos.y = Top; Pos.y <= Bottom; ++Pos.y)
if (Pos.x < mSize.x && Pos.y < mSize.y)
Tiles.push_back(&getTileAtPos(Pos));
return Tiles;
}
const std::vector<const Tile*>& Level::calculateTilesWithinAABB(const gm::AABB& Box) const
{
static std::vector<const Tile*> Tiles;
Tiles.clear();
/* Same duplicated code. */
return Tiles;
}
I want to remove the duplicate commented out code. How can it be done?
There's a related question, How do I remove code duplication between similar const and non-const member functions?, but the solution doesn't work in this case since you cannot cast between std::vector<const T*>
and std::vector<T*>
.
Here's a compilable version the above code for experimenting.
Possible solutions:
- Make the duplicate code a macro, and use the macro in the two functions.
In the non-
const
version, usereinterpret_cast
to cast fromstd::vector<const Tile*>
tostd::vector<Tile*>
:return reinterpret_cast<const std::vector<Tile*>&>( const_cast<const Level*>(this)->calculateTilesWithinAABB(Box));
which compiles and seems to work. But is it safe / guaranteed to work on all major compilers?