Say I want to make 2 versions of a class - a thread safe version which will use lock guards on all mutating operations, and a 'thread dangerous' one which won't and will presumably run faster in a single-threaded client.
A bit like this:
#include <type_traits>
#include <mutex>
template <bool THREADSAFE>
class wibble {
private:
typename std::enable_if<THREADSAFE, std::mutex>::type mtx_;
};
wibble<true> threadsafe; // ok
wibble<false> thread_dangerous; // compiler error
Thanks!
The usual way to achieve this is via conditional derivation: https://godbolt.org/z/ahxGqj76c
#include <mutex>
#include <type_traits>
struct threadsafe_base
{
mutable std::mutex mtx_;
};
struct threadunsafe_base
{};
//public derivation used for brevity
template<bool THREADSAFE>
struct wibble : std::conditional_t<THREADSAFE, threadsafe_base, threadunsafe_base>
{};
template<typename T>
void doStuff(const T& arg)
{
std::unique_lock<std::mutex> lck(arg.mtx_);
//do sth
}
int main(int, char*[])
{
wibble<true> threadsafe;
wibble<false> thread_dangerous;
doStuff(threadsafe);
// doStuff(thread_dangerous); //this should fail to compile
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With