c++ - 将基类 vector 传递给采用父类(super class) vector 的函数

标签 c++ inheritance vector abstraction supertype

在我的代码中,我有一个 SuperType它有两个子类型......现在我有一个std::vector<SubTypeA>&并且需要将其传递给一个函数,该函数遍历 vector 并从 SuperType 调用 函数...我需要对两种子类型都执行此操作。

(父类(super class)型还不是虚拟的,但我需要在某个时候使它成为虚拟的,因为它只是两个子类型的公共(public)部分,不能有它的实例)

这是一个最小的(非)工作示例:

#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.
}

传递迭代器也是一种解决方案。


旁注:我得到 my_variable来自另一种类型:

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

而且我不想更改容器,所以 std::vector<SubTypeA>&是的。

最佳答案

在 C++ 中引用和指针类型 SuperSubTypeA是协变的,但是 std::vector<Super>std::vector<SubTypeA>不是。您可以使用指针 vector 或对基类的引用来实现您想要的:

#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.
}

根据评论中的建议更新

关于c++ - 将基类 vector 传递给采用父类(super class) vector 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47176028/

相关文章:

C#构造函数执行顺序

c# - 继承的 C# 类丢失 "Reference"

c++ - 派生类无法访问继承的函数?

C++ 数组与 vector

c++ - 为什么填充我的 std::vector 的运行时间在 0 到 ~16 毫秒之间跳跃?

c++ - 在 C++ 中将 vector 声明为全局变量

c++ - 当使用自定义比较器交换相同类型的标准库容器时,为什么会发生此错误?

c++ - 将 printf 更改为 cout 语句

c++ - 如何在C++项目中使用zxing?

c++ - 什么是 Mac 上 C++/Windows SendMessage() 的等效项(如果有)?