我想传递一个填充了基于对象的同一类的向量。两者std::reference_wrapper
和无参考都不能解决它。解决这个问题的正确方法是什么?
class MyClass
{
public:
MyClass(int){};
virtual void print() const {
std::cout<<"MyClass"<<std::endl;
}
};
class MySubClass : public MyClass
{
public:
MySubClass(int a):MyClass(a){};
virtual void print() const {
std::cout<<"MySubClass"<<std::endl;
}
};
void test(const std::vector<std::reference_wrapper<MyClass>>& v)
{
for (const auto& c : v) {
c.get().print();
}
}
void test(const std::vector<MyClass>& v)
{
for (const auto& c : v) {
c.print();
}
}
int main()
{
{
MySubClass s(2);
std::vector<MyClass> v;
v.push_back(s);
test(v);//print MyClass, but I need MySubClass
}
{
MySubClass s(2);
std::vector<std::reference_wrapper<MyClass>> v;
v.push_back(s);
test(v);//print MySubClass
test({2});
test({s});//wrong ambigious
}
return 0;
}