c++ - 当需要基类作为参数时无法传递子类的 vector

标签 c++ casting stdvector

我有一个类A及其子类 B和一个采用 std::vector<A> 的方法.而且我不能通过传递 std::vector<B> 来让它工作.

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

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

提前致谢!

最佳答案

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

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() 的重载行为是不同的(即当考虑此模板时)。

关于c++ - 当需要基类作为参数时无法传递子类的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51430486/

相关文章:

c++ - C++ 中的位数组

c++ - 尝试读取对象 vector 时程序崩溃

c++ - 如何使用 C++ 加密文件夹?

c++ - Eclipse C++ 项目未解析 LD_LIBRARY_PATH 包含变量

c++ - 如何减少 C++ 中数据的内存大小?

c++ - 用 boost::spirit 解析成一个 vector<vector<double>>

c++ - vector<int*>.push_back() 正在覆盖 front() 指向的值

swift 无法将类型 'Int' 的值分配给类型 'String'

python - dbus-python 如何获得本地类型的响应?

C++ 在作为函数传递后从父级转换为子级?