'Template virtual method for each type
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&) {}
Solution 1:[1]
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
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
