我想创建一个带/不带线程安全的池。如果池不是线程安全的,我不想定义互斥字段,因此我使用了std::conditional。然而,由于它没有完全做到我想要的,而且创建了两个“类型”选项,所以我选择了“int8(char)”作为被动化的互斥类型。(相反,我希望整个定义都消失)
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;
}
};
正如您所看到的,在方法内部我使用了“constexpr if”,它的效果非常好,因为它可以禁用整个代码块。
主要问题:除了“std::conditional”之外,是否有更好的方法来禁用整个定义,例如“Mutex mutex;”?
附加问题:对于“int8 mutex”,我收到了“未初始化变量”的警告,我必须用“0”进行初始化。如何以“std::conditional”方式在编译时执行此操作。
this->m_mutex
或者PoolBase<threadSafe>::m_mutex
的方式访问它,因为它是一个依赖于模板参数的名称。请参考https://dev59.com/dHRB5IYBdhLWcg3weXOX。 - user7860670