Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  • std::lock_guard::mutex_type
  • std::unique_lock::mutex_type
  • std::scoped_lock::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?

like image 296
Fantastic Mr Fox Avatar asked Nov 08 '22 07:11

Fantastic Mr Fox


1 Answers

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);
like image 104
Caleth Avatar answered Nov 14 '22 22:11

Caleth