0

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:

  1. Make the duplicate code a macro, and use the macro in the two functions.
  2. In the non-const version, use reinterpret_cast to cast from std::vector<const Tile*> to std::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?

Community
  • 1
  • 1
emlai
  • 37,861
  • 9
  • 87
  • 140
  • How significant is the duplicated code? Is it something that could be macro-itized?. – P. Hinker Oct 18 '15 at 13:27
  • 8 lines atm, but it might grow in the future. Yes, macro-itizing it would be one solution, not a particularly beautiful one though. – emlai Oct 18 '15 at 13:31
  • Could you elaborate more about your duplicated code? Which part exactly isn't compatible anymore? The a possible solution would range from auto code deduction to a templated method... it's very dependent on the duplicated code. – Denis Blank Oct 18 '15 at 13:31
  • @DenisBlank Added the code to the question. – emlai Oct 18 '15 at 13:38
  • Why is the first member function non-const? – Karoly Horvath Oct 18 '15 at 13:41
  • @KarolyHorvath Because it returns pointers to non-const `Tile`s, that are part of the `Level` and modifying them should be considered a modification of the `Level`. – emlai Oct 18 '15 at 13:45

0 Answers0