1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include<boost/preprocessor/seq/enum.hpp>
#define BASE_ACCEPT(TYPES) \
virtual void accept(Visitor<BOOST_PP_SEQ_ENUM(TYPES)>* v) =0;
#define ACCEPT(TYPES) \
void accept(Visitor<BOOST_PP_SEQ_ENUM(TYPES)>* v) \
{ v->visit(*this); }
template<class...>
struct Visitor;
template<class T>
struct Visitor<T>
{
virtual ~Visitor(){}
virtual void visit(T&) =0;
};
template<class T, class... Arg>
struct Visitor<T,Arg...> : Visitor<T>, Visitor<Arg...>
{
using Visitor<T>::visit;
using Visitor<Arg...>::visit;
};
//Exemple
//Hiérarchie
struct A;
struct B;
struct C;
struct Base
{ virtual ~Base(){}
BASE_ACCEPT((A)(B)(C)) };
struct A : Base
{ ACCEPT((A)(B)(C)) };
struct B : Base
{ ACCEPT((A)(B)(C)) };
struct C : Base
{ ACCEPT((A)(B)(C)) };
//Un visiteur
#include<iostream>
struct MyVisitor : Visitor<A,B,C>
{
void visit(A&)
{ std::cout << 0; }
void visit(B&)
{ std::cout << 1; }
void visit(C&)
{ std::cout << 2; }
};
int main()
{
Base* b1 = new A();
Base* b2 = new B();
Base* b3 = new C();
Visitor<A,B,C>* v = new MyVisitor();
b1->accept(v);
b2->accept(v);
b3->accept(v);
int i;
std::cin >> i;
} |
Partager