Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33904

What is the use case for mutex_type specified in `unique_lock`, `scoped_lock` and `lock_guard`?

The c++11 mutex RAII types for guarding std::mutex all have a typedef:

typedef Mutex mutex_type;

What is the point of this member typedef? At first I thought it could be used to generalize creating an object for moving the lock (in the case of the unique_lock) for example:

template<SomeLock>
void function(SomeLock in)
    SomeLock::mutex_type newMutex;
    //Do something

But I cannot imagine a use for this.

A further note is that it doesn't appear to be used anywhere in the implementation of the locks (at least not in VisualC++).

What is a use case of the member mutex_type?

Upvotes: 5

Views: 383

Answers (1)

Caleth
Caleth

Reputation: 63029

Having a type alias for each template parameter is normal in the standard library. Off hand, I can't recall a template in std that doesn't alias all it's template parameters as member types

Having a distinct name for a type alias in a group of related classes allows for that group to be easily distinguished from other classes, e.g. for SFINAE

template<typename Lock, typename = std::void_t<Lock::mutex_type>>
void usesLock(Lock lock); // Substitution failure for most instantiations of Lock

It also allows you to easily specify a parameter of appropriate type.

template<typename Lock>
void usesMutex(Lock::mutex_type & mut);

Upvotes: 1

Related Questions