Using Templates to add virtual tables to non-virtual classes So I have these classes that are meant to be low level and fast. I don't want them to generally be virtual - rather I want the functions to be inline.

In this case they are mutex implementations:

class MutexOne
{
public:
   void lock        () { /* implementation inline */ }   
   bool tryLock     () { /* implementation inline */ }  
   void unlock      () { /* implementation inline */ }
   void reset       () { /* implementation inline */ }

   static const char* implementationName() { return "MutexOne"; }
};

class MutexTwo
{
public:
   void lock        () { /* implementation inline */ }   
   bool tryLock     () { /* implementation inline */ }  
   void unlock      () { /* implementation inline */ }
   void reset       () { /* implementation inline */ }

   static const char* implementationName() { return "MutexTwo"; }
};

... etc ...


All the mmutexes have the same api. Within a testing framework I kind of wish they were virtual so that I can do something like:

testMutexImplementation( MutexVirtual&amp; mutex )
{
    mutex.lock();  // etc... do a lot of complex validating
}


So within the testing framework I wish I had a nice clean virtual base class interface. But in production I don't want to pay for a virtual function on every mutex operation many of which are like 2-3 opcode in the general case.

So I thought of this way to use templates to add a virtual table after the fact, only when I need it.

So I start by creating the desired base class:

class MutexVirtual
{
public:

   virtual void lock        () = 0;
   virtual bool tryLock     () = 0;
   virtual void unlock      () = 0;
   virtual void reset       () = 0; 

   virtual const char* implementationName() = 0;
};


And then use template magic to fill in the virtual table:

template &lt; typename T &gt; class MutexPostVirtual : public MutexVirtual, public T
{
public:
   void lock           () { T::lock(); }
   bool tryLock        () { return T::tryLock(); }
   void unlock         () { T::unlock(); }
   void reset          () { T::reset(); } 

   const char* implementationName() { return T::implementationName(); }
};


I'm pretty happy and it works great:

MutexPostVirtual&lt;MutexOne&gt; mutex1;
MutexPostVirtual&lt;MutexTwo&gt; mutex2;

testMutexImplementation( mutex1 );
testMutexImplementation( mutex2 );


I can't help thinking that maybe there is a cleaner simpler way? How can this code be better?
I don't know what framework you are using for your tests but gtest has type parametrised tests that you can use to test all the implementations​ with the same tests.

By using this feature you wouldn't even need the code to begin with, which in my book is the best code: the code you never wrote :)