I want to have a class that receives a mutex type as template parameter to be (conditionally) thread-safe. If the mutex type is equal to NoMutex(my mutex empty implementation), I don't want to add this mutex member to my class so I can save space. I want to do something like this:
class NoMutex{
// Same interface as std::mutex but empty implementation
// so optimization can remove unnecessary function calls
};
template <class Mutex>
class MyClass {
public:
// Actually I want to hide it somehow. I dont want it to occupy any space if Mutex == NoMutex
some_template_trick<std::is_same_v<Mutex, NoMutex, void, Mutex> mutex;
void someFunction(){
std::unique_lock<Mutex> l(getMutex()); // I want to use std::unique_lock here
// do some concurrent stuff
}
Mutex& getMutex(){
if constexpr(std::is_same_v<Mutex, NoMutex>){
//ok... return reference to temporary is wrong, but i'm hopping
//that gcc will realize there is nothing to be done once all implementations
//are empty.
return NoMutex();
}
return mutex;
}
};
I don't want to specialize the class nor create lock() unlock() methods, I want them to be managed by std::unique_lock(); Is it possible?
Thanks in advance!