删除(非)const成员函数之间的重复,返回指向(非)const对象

时间:2015-10-18 13:17:20

标签: c++ const stdvector code-duplication member-functions

我有一个成员函数的两个重载:

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;
}

我想删除重复注释掉的代码。怎么办呢?

有一个相关的问题,How do I remove code duplication between similar const and non-const member functions?,但解决方案在这种情况下不起作用,因为您无法在std::vector<const T*>std::vector<T*>之间进行投射。

Here是上述试验代码的可编译版本。

可能的解决方案:

  1. 将重复的代码设为宏,并在两个函数中使用宏。
  2. 在非const版本中,使用reinterpret_caststd::vector<const Tile*>投射到std::vector<Tile*>

    return reinterpret_cast<const std::vector<Tile*>&>(
               const_cast<const Level*>(this)->calculateTilesWithinAABB(Box));
    

    编译并且似乎有效。但是对所有主要编译器都有效吗?

0 个答案:

没有答案
相关问题