Search code examples
c++classtemplatesc++17default-constructor

std::default_constructible for templated class parameter


I'm fairly new to c++-templates, and at the point where I'm realizing that I'm probably doing template meta-programming. What I want is to achieve the following definition:

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

I want a compile-time check whether or not the provided template type T has a default constructor, and otherwise result in a compile error.

Am I using the correct approach? Thanks in advance.


Solution

  • std::enable_if is pointless on a class template. It's useful for overloaded function templates, and less commonly, for partial specializations of a class template; that's where SFINAE applies.

    If you simply want to prevent PoolAllocator from compiling if T is not default-constructible, use 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
    };