Skip to content

Instantly share code, notes, and snippets.

@alf-p-steinbach
Created June 5, 2021 18:56
Show Gist options
  • Save alf-p-steinbach/8faeadf8b3a800bde99690ad4932169b to your computer and use it in GitHub Desktop.
Save alf-p-steinbach/8faeadf8b3a800bde99690ad4932169b to your computer and use it in GitHub Desktop.
Visitor pattern in separate files
#include "Visitable.hpp"
struct Cat: Visitable
{
void hunt_birds() { throw "Hunting birds..."; }
void accept( Doer& doer ) override { doer.deal_with( *this ); }
};
#include "Cat.hpp"
auto create_cat() -> Visitable* { return new Cat; }
#include "Person.hpp"
auto create_person() -> Doer* { return new Person; }
#pragma once
struct Cat;
struct Phone;
struct Doer
{
virtual ~Doer() {}
virtual void deal_with( Cat& ) = 0;
virtual void deal_with( Phone& ) = 0;
};
#include "Visitable.hpp"
extern auto create_person() -> Doer*;
extern auto create_cat() -> Visitable*;
#include <stdio.h>
#include <memory>
using std::unique_ptr;
auto main() -> int
{
using C_str = const char*;
try {
auto doer = unique_ptr<Doer>( create_person() );
auto object = unique_ptr<Visitable>( create_cat() );
object->accept( *doer ); // "Hunting birds..."
} catch( const C_str s ) {
printf( "%s\n", s );
}
}
#include "Doer.hpp" // Not really necessary but to be clear.
#include "Cat.hpp"
#include "Phone.hpp"
struct Person: Doer
{
void deal_with( Cat& cat ) override { cat.hunt_birds(); }
void deal_with( Phone& phone ) override { phone.call_999(); }
};
#include "Visitable.hpp"
struct Phone: Visitable
{
void call_999() { throw "Calling 999!"; }
void accept( Doer& doer ) override { doer.deal_with( *this ); }
};
#pragma once
#include "Doer.hpp"
struct Visitable
{
virtual ~Visitable() {}
virtual void accept( Doer& doer ) = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment