0

In my code, I have a SuperType which has two SubTypes ... now I have a std::vector<SubTypeA>& and need to pass this to a function which iterates over the vector and calls only functions from the SuperType ... I need to do this with both subtypes.

(The supertype is not virtual yet, but I need to make it virtual at some point, because it is just the common part of the two subtypes and there can't be an instance of it)

Here is a minimal (non)working example:

#include <vector>
struct Super {
    // stuff and functions
};
struct SubTypeA : public Super {
    // stuff and functions
};

void func(const std::vector<Super>& sup) {
    for (auto& elem: sup) {
        // do things
    }
    return;
}

int main() {
    std::vector<SubTypeA> v; // I get this from another place
    std::vector<SubTypeA>& my_variable = v; // this is what I have in my code
    func(my_variable); // does not work.
}

passing an iterator would be a solution, too.


Sidenote: I get the my_variable from another type:

struct SomeContainer {
    std::vector<SubTypeA> a;
    std::vector<SubTypeB> b;
}

And I wouldn't like to change the container, so std::vector<SubTypeA>& it is.

musicmatze
  • 3,603
  • 6
  • 26
  • 43
  • 1
    `std::vector` is different type from `std::vector`, and cannot be converted from one to another losslessly due to [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing). – Algirdas Preidžius Nov 08 '17 at 09:37
  • 4
    Possible duplicate of [How to pass a vector of a Child class in to a function expecting a vector of Parent class?](https://stackoverflow.com/questions/14992961/how-to-pass-a-vector-of-a-child-class-in-to-a-function-expecting-a-vector-of-par) – StaticBeagle Nov 08 '17 at 09:40

1 Answers1

3

In c++ references and pointers of types Super and SubTypeA are covariant, but std::vector<Super> and std::vector<SubTypeA> are not. You can use vector of pointers or references to base class to achieve what you want:

#include <vector>
struct Super {
    // stuff and functions
};
struct SubTypeA : public Super {
    // stuff and functions
};

void func(std::vector<std::reference_wrapper<Super>>& sup) {
    for (Super& elem: sup) {
        // do things
    }
    return;
}

int main() {
    std::vector<SubTypeA> v; // I get this from another place
    // using vector of references to base class
    std::vector<std::reference_wrapper<Super>> my_variable(v.begin(), v.end());        

    func(my_variable); // does not work.
}

Updated as recommended in comments

user2807083
  • 2,606
  • 4
  • 25
  • 35