How to properly use tag dispatching to pick a constructor

Viewed 1266

I'm trying to implement a set of mutex and lock classes for an embedded system. I've never used tag dispatching before, and I'm not sure if I'm doing it right. The description included in the boost documentation simply has this:

struct input_iterator_tag { };

and uses it to pick a specialized template function. I don't have a template, I just want to pick a specific constructor based on the presence of a tag:

// in mutex.h:

struct TryLock { };
// defined nowhere, i.e. there's no cpp file for this:
extern TryLock try_lock; 

template<typename MutexType>
class ScopedLock
{
  public:
    ScopedLock(MutexType& mtx) : m_mtx(mtx), m_acquired(true)
    {
      m_mtx.lock();
    }
    ScopedLock(MutexType& mtx, TryLock) : m_mtx(mtx)
    {
      m_acquired = m_mtx.tryLock();
    }
  ...
}

and somewhere in my code I have a mutex which I want to lock:

Mutex mtx;
ScopedLock<Mutex> lock(mtx, try_lock);

This compiles fine and works. I'm just curious if I can get rid of the extern TryLock try_lock;, as I have the impression that it's somewhat superfluous.

1 Answers
Related