c++ - 当需要基类作为参数时,无法传递子类的向量
问题描述
我有一个类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.
提前致谢!
解决方案
一种解决方案是使用模板。例如
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()
是不同的(即,当考虑此模板时)。
推荐阅读
- firebase - Flutter/Firebase - type 'Future
' is not a subtype of type 'int' - c - Generate integer random number using available binaryrandom (which return 0 or 1) function
- python - How to resolve graph2vec error invalid literal for int()?
- android - 使用 ViewModel 未在 Webview 中加载 URL
- python - While trying to display wav file using scipi im getting the following error "ushort format requires 0 <= number <= 0xffff"
- python-3.x - 使用 PyInstaller 缺少按钮图标
- java - how can I get the only entered values from an array?
- ansible - Ansible Tower (AWX) - using secure variables in a playbook?
- spring-mvc - Debugging the server side code after clicking on gmail
- web-scraping - How do I scrape elements at the same level from a website using bs4