我有一个类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/