将 std:vector<reference_wrapper<Base>> 转换为 std:vector<reference_wrapper<Derived>> 运行时错误时间:0 内存:3412 signal:6

Transform std:vector<reference_wrapper<Base>> to std:vector<reference_wrapper<Derived>> Runtime error time: 0 memory: 3412 signal:6

我正在尝试将对 Base 对象的引用向量转换为对 Derived 对象的引用向量。一切编译正常,但我收到此错误:运行时错误时间:0 内存:3412 signal:6

这是我的代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

struct B {
    B(int i) { b = i; }
    virtual ~B() {}
    int b;
};

struct D: public B {
    D(int i): B(i) {}
};

typedef vector<reference_wrapper<B>> refB;
typedef vector<reference_wrapper<D>> refD;

void dynamicCast(refB &b, refD &d)
{
    for(const auto& bb: b)
    {
        d.push_back(dynamic_cast<D&> (bb.get()));
    }
}

int main() {
    vector<B*> numbers;
    refB refNumbers;
    refD dNumbers;

    for(int i = 0; i < 10; i++)
    {
        numbers.push_back(new B(2*i));
        refNumbers.push_back(*numbers[i]);
    }

    dynamicCast(refNumbers, dNumbers);

    return 0;
}

dynamicCast() 函数有什么问题?

编辑: @John Zwinck 的回答有帮助,但是当我尝试在我的代码中执行此操作时,出现编译错误:

cannot dynamic_cast '(& obj)->std::reference_wrapper<_Tp>::get()' (of type 'class MEPObject') to type 'class MEPGene&' (target is not pointer or reference to complete type) genes.push_back(dynamic_cast (obj.get()));

class MEPObject;
class MEPGene;
typedef std::vector<std::reference_wrapper<MEPObject>> MEPObjects;
typedef std::vector<std::reference_wrapper<MEPGene>> MEPGenes;

void dynamicCast(MEPObjects &objects, MEPGenes &genes)
{
    for(const auto &obj: objects)
    {
        genes.push_back(dynamic_cast<MEPGene&> (obj.get()));
    }
}
                                                      ^

dynamicCast()没有问题。问题在这里:

    numbers.push_back(new B(2*i));

您只能构造 B 的实例,它是基础 class。您不可能将它们转换为 D 这是派生的 class.

也许您打算构造派生实例并将它们存储在您对 base 的引用向量中。