Getting a vector into a function that expects a vector<Base*>

后端 未结 9 1813
日久生厌
日久生厌 2020-11-29 07:11

Consider these classes.

class Base
{
   ...
};

class Derived : public Base
{
   ...
};

this function

void BaseFoo( std::ve         


        
9条回答
  •  攒了一身酷
    2020-11-29 08:11

    one option is to use a template

    template
    void BaseFoo( const std::vector& vec)
    {
     ...
    }
    

    The drawback is that the implementation has to be in the header and you will get a little code bloat. You will wind up with different functions being instantiated for each type, but the code stays the same. Depending on the use case it's a quick and dirty solution.

    Edit, I should note the reason we need a template here is because we are trying to write the same code for unrelated types as noted by several other posters. Templates allow you do solve these exact problems. I also updated it to use a const reference. You should also pass "heavy" objects like a vector by const reference when you don't need a copy, which is basically always.

提交回复
热议问题