This is a follow-up to this question.
We can implement the visitor pattern for the problem in the previous question, as suggested in this answer:
class Base {
foo(Parent& p) {
p.accept(*this);
}
virtual void visit(Child_A&) = 0;
virtual void visit(Child_B&) = 0;
};
class Parent {
virtual void accept(Base&) = 0;
};
class Child_A: Parent {
void accept(Base& v) {
v.visit(*this);
}
};
class Child_B: Parent {
void accept(Base& v) {
v.visit(*this);
}
};
class Derived_A: Base {
void treat_same(Parent&) {
// ...
}
void visit(Child_A& a) {
treat_same(a);
}
void visit(Child_B& b) {
treat_same(b);
}
};
class Derived_B: Base {
void visit(Child_A&) {
// ...
}
void visit(Child_B&) {
// ...
}
};
But now consider if foo
expects a std::vector<std::shared_ptr<Parent>> const&
as its argument.
Then how can we implement visitor pattern for the problem? Is it possible?
EDIT
foo
passes std::vector<std::shared_ptr<Parent>> const&
to another class, state
. But if all the objects in the vector are of type Child_A
it calls state.method_A
, if all objects in the vector are of type Child_B
it calls state.method_B
and otherwise calls state.method_C
. Only state
works directly with parent
classes.
I hope this clears things a bit.