Home > front end >  Template virtual method for each type
Template virtual method for each type

Time:04-23

If I have a template as such:

template <typename ... TYPES>
class Visitor {
public:
    //virtual void visit(...) {}
};

Is there a way I can have C generate virtual methods "for each" type in the list?

For example, conceptually, I would like

class A;
class B;
class C;

class MyVisitor : public Visitor<A,B,C>;

To have the following virtual methods

virtual void visit(const A&) {}
virtual void visit(const B&) {}
virtual void visit(const C&) {}

CodePudding user response:

You could add a base class template for Visitor and for each type in TYPES that defines a visit function for the type provided and then you would inherit from those base classes. That would look like

template <typename T>
class VisitorBase
{
public:
    virtual void visit(const T&) { /* some code */ }
};

template <typename ... TYPES>
class Visitor : public VisitorBase<TYPES>... 
{
public:
    using VisitorBase<TYPES>::visit...; // import all visit functions into here
};
  • Related