[英]std::default_constructible for templated class parameter
我是 c++ 模板的新手,此时我意识到我可能正在做模板元编程。 我想要的是实现以下定义:
#include <type_traits>
// T must be default-constructible
template<class T, std::enable_if<std::is_default_constructible<T>>>
class PoolAllocator
{
public:
PoolAllocator(unsigned int numItems);
~PoolAllocator();
T* Alloc();
void Free(T* item);
private:
struct mPoolItem
{
T item;
mPoolItem* next;
};
mPoolItem* mpPool;
mPoolItem* mpFreePointer; // points to the first free element or nullptr
};
我想要编译时检查提供的模板类型T
是否具有默认构造函数,否则会导致编译错误。
我使用的方法正确吗? 提前致谢。
std::enable_if
在 class 模板上毫无意义。 它对于重载的 function 模板很有用,对于 class 模板的部分特化不太常见; 这就是 SFINAE 适用的地方。
如果您只是想在T
不可默认构造时阻止PoolAllocator
编译,请使用static_assert
:
template<class T>
class PoolAllocator {
static_assert(std::is_default_constructible_v<T>,
"Parameter must be default-constructible");
// The rest of implementation here
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.