Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling field definitions at compile-time

Tags:

c++

i want to create a Pool with/without thread-safe. I dont want to define a mutex field, if the pool is not thread-safe so i used std::conditional, however because it's not doing exactly what i want, and creates two "type" options, i chose "int8 (char)" as passivised mutex type. (Instead i want the whole definition is gone)

template<typename T, bool threadSafe = true>
class Pool
{
private:
    //Mutex mutex; this is the field i want it to be DISAPPEARED, i modified it as below
    std::conditional<threadSafe, Mutex, int8>::type mutex;
protected:
    static constexpr item_type_size_datatype TypeSizeX = sizeof(T) + sizeof(size_t);
public:
    Pool(size_t clusterItemCount) : ClusterItemCount(clusterItemCount),
        ClusterByteSize(clusterItemCount* TypeSizeX)
    {
#ifdef CriticalSection
        if constexpr (threadSafe)
            InitializeCriticalSection(&mutex);
#endif
    }
    ~Pool()
    {
        Clear();

#ifdef CriticalSection
        if constexpr (threadSafe)
            DeleteCriticalSection(&mutex);
#endif
    }

    T* Occupy(bool& outFirstTime)
    {
        if constexpr (threadSafe)
        {
            MutexLock(mutex);
        }

        //do the occupation

        if constexpr (threadSafe)
        {
            MutexUnlock(mutex);
        }

        return result;
    }
};

as you can see, inside methods i used "constexpr if" that works like a charm because it disables whole code blocks.

Main Question: Is there a better way to disable whole definition such as "Mutex mutex;" other than "std::conditional"

Additional Question: I am getting "uninitialized variable" warning for "int8 mutex", i have to initialized with "0".. how can i do this at compile-time with "std::conditional" manner.

like image 589
Ibrahim Ozdemir Avatar asked Oct 20 '25 12:10

Ibrahim Ozdemir


1 Answers

This can be achieved via template specialization, for example:

template<bool threadSafe>
class PoolBase;

template<>
class PoolBase<false>
{// empty
};

template<>
class PoolBase<true>
{
   protected: Mutex m_mutex;
};

template<typename T, bool threadSafe = true>
class Pool: private PoolBase<threadSafe>
{
...

like image 146
user7860670 Avatar answered Oct 23 '25 01:10

user7860670



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!