C++ features by examples

Visitor pattern More...

Collaboration diagram for Visitor:

Classes

struct  Component
 accepts a pure virtual Visitor More...
 
struct  Visitor
 is a pure virtual visitor of Sample_component and other specific components More...
 
struct  Sample_component
 one of many components is independed from Sample_visitor and implemenation of function visit. More...
 

Functions

string client_visit (const forward_list< unique_ptr< Component > > &components, const forward_list< unique_ptr< Visitor > > &visitors)
 knows only virtual visitor and component More...
 
void visitor_demo ()
 

Detailed Description

Visitor pattern

https://refactoring.guru/design-patterns/visitor/cpp/example

Function Documentation

◆ client_visit()

string client_visit ( const forward_list< unique_ptr< Component > > &  components,
const forward_list< unique_ptr< Visitor > > &  visitors 
)

knows only virtual visitor and component

Definition at line 469 of file patterns.cpp.

472{
473 string res;
474 for (auto&& comp : components)
475 for (auto&& vis : visitors) {
476 res += string(__func__) + " > " + comp->component_accept(*vis.get());
477 }
478 return res;
479}
Here is the caller graph for this function:

◆ visitor_demo()

void visitor_demo ( )

Call hierarchy:

visitor_demo client_visit component_accept visit component_method

is one of many specific visitors with custom method visit Per each of the possible pairs of Sample_visitor and Sample_component

overloaded function for each component

Definition at line 491 of file patterns.cpp.

492{
495 struct Sample_visitor
496 : public Visitor {
498 string visit(const Sample_component& c) const override {
499 return string(__func__) + " > " + c.component_method();
500 }
501 };
502
503 forward_list<unique_ptr<Component>> components;
504 components.emplace_front(new Sample_component);
505 Sample_visitor v;
506 forward_list<unique_ptr<Visitor>> visitors;
507 visitors.emplace_front(new Sample_visitor);
508 assert(client_visit(components, visitors) ==
509 "client_visit > component_accept > visit > component_method");
510}
string client_visit(const forward_list< unique_ptr< Component > > &components, const forward_list< unique_ptr< Visitor > > &visitors)
knows only virtual visitor and component
Definition: patterns.cpp:469
one of many components is independed from Sample_visitor and implemenation of function visit.
Definition: patterns.cpp:459
string component_method() const
is not virtual
Definition: patterns.cpp:464
is a pure virtual visitor of Sample_component and other specific components
Definition: patterns.cpp:448
virtual string visit(const Sample_component &) const =0
overloaded function for each component
Here is the call graph for this function:
Here is the caller graph for this function: