How to create a constraint around a constraint that template member functions cannot be virtual

I am facing a design problem where (in C ++) I would like a template member function (of a non-classical class) to be virtual, and I wonder if there is a nice, elegant way to solve the problem.

The script is on, I have machines that handle common elements. I use an abstract base class for machines with a virtual process function (Item) so that each machine can define its own unique processing method. The problem is that elements are also β€œuniversal” because they provide specific interfaces for how they can be processed. For reasons (mainly for performance ... no vtable overhead), I would like to use compile-time polymorphism for these elements. So now every machine will have such an interface as:

class Machine { public: template <typename T> virtual void process(T& item) = 0; }; 

However, this is not possible in C ++, because template member functions cannot be virtual. of course, I can make a machine class a template like Item T, but it adds more headaches for me in a larger design scheme, and in fact no other part of the Machine class depends on Item ... this is just an argument to the process () function ,

Is there a better way around this or any suggestions on how to provide such a common family of machines that handle a family of common elements (where the elements use compile-time polymorphism). I am with a deep end in terms of my design.

Rate any suggestions

+6
c ++ virtual templates
source share
1 answer

Usually used double dispatch.

 class Machine; class Item { public: virtual void bounce(Machine& mach); }; class Machine { public: template<typename T> void process(T& t); virtual void process(Item& i) { return i.bounce(*this); } }; template<typename T> class CRTPItem { public: virtual void bounce(Machine& mach) { return mach.process(*(T*)this); } }; class ConcreteItem : public CRTPItem<ConcreteItem> { public: // blah blah }; 

In this case, you do not need virtual overhead for the entire ConcreteItem interface, and they do not need anything in common, only one bounce function, created automatically for you, inheriting from CRTPItem . These are just two virtual calls, not the one you originally had, unlike the need to call vtable for all Item functions, and the interface can still save all the powerful input types that you could have if you could create virtual templates.

+3
source share

All Articles