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

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

Consider these classes.

class Base
{
   ...
};

class Derived : public Base
{
   ...
};

this function

void BaseFoo( std::ve         


        
相关标签:
9条回答
  • 2020-11-29 07:58

    If you dealing with a third-party library, and this is your only hope, then you can do this:

    BaseFoo (*reinterpret_cast<std::vector<Base *> *>(&derived));
    

    Otherwise fix your code with one of the other suggesstions.

    0 讨论(0)
  • 2020-11-29 08:10

    If std::vector supported what you're asking for, then it would be possible to defeat the C++ type system without using any casts (edit: ChrisN's link to the C++ FAQ Lite talks about the same issue):

    class Base {};
    class Derived1 : public Base {};
    class Derived2 : public Base {};
    
    void pushStuff(std::vector<Base*>& vec) {
        vec.push_back(new Derived2);
        vec.push_back(new Base);
    }
    
    ...
    std::vector<Derived1*> vec;
    pushStuff(vec); // Not legal
    // Now vec contains a Derived2 and a Base!
    

    Since your BaseFoo() function takes the vector by value, it cannot modify the original vector that you passed in, so what I wrote would not be possible. But if it takes a non-const reference and you use reinterpret_cast<std::vector<Base*>&>() to pass your std::vector<Derived*>, you might not get the result that you want, and your program might crash.

    Java arrays support covariant subtyping, and this requires Java to do a runtime type check every time you store a value in an array. This too is undesirable.

    0 讨论(0)
  • 2020-11-29 08:11

    one option is to use a template

    template<typename T>
    void BaseFoo( const std::vector<T*>& 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.

    0 讨论(0)
提交回复
热议问题