首页 > 解决方案 > 当需要基类作为参数时,无法传递子类的向量

问题描述

我有一个类A及其子类B和一个采用std::vector<A>. 而且我无法通过传递来使其工作std::vector<B>

我虽然如果子类B可以转换为A,我应该能够将 s 的向量传递B给采用 s 向量的方法A。我怎样才能正确地做到这一点?

#include <iostream>
#include <vector>

class A {

    public:

        A() {}
};

class B: public A {

    public: 

        B(): A() {}
};

void method(std::vector<A> a) {}

int main() {
    std::vector<B> b;
    method(b);

    return 0;
}

编译时:

g++ ex-cast-tag.cpp -std=c++11

ex-cast-tag.cpp:22:5: error: no matching function for call to 'method'
    method(b);
    ^~~~~~
ex-cast-tag.cpp:18:6: note: candidate function not viable: no known conversion from 'vector<B>' to 'vector<A>'
  for 1st argument
void method(std::vector<A> a) {}
     ^
1 error generated.

提前致谢!

标签: c++castingstdvector

解决方案


一种解决方案是使用模板。例如

template<typename C>
std::enable_if_t<std::is_base_of<A,C>::value>
method(std::vector<C> const&a) 
{
    // assume that a[i] is an A (derived or actually the same)

}

在这里,我使用SFINAE来确保它C实际上是A或派生自A. 但您也可以static_assert改用。在这种情况下,您会收到更好的错误消息,但 的重载行为method()是不同的(即,当考虑此模板时)。


推荐阅读