Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can c++ class attributes be conditionally compiled

Tags:

c++

enable-if

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!

like image 681
VorpalSword Avatar asked Apr 17 '26 23:04

VorpalSword


1 Answers

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;
}

like image 64
alagner Avatar answered Apr 20 '26 12:04

alagner