Search code examples
c++c++14type-traitsallocator

what is the correct way to test if a type is an allocator?


Writing allocator_traits<T>::value_type in a SFINAE context seems like a workable way to test if a type T is, in fact, an allocator. This is however not particularly elegant and I have been burned by corner cases in the past.

Therefore my question: how best might one implement an is_allocator<T> traits containing a ::value of true in the case where T is an allocator and ::false otherwise?


Solution

  • Writing allocator_traits<T>::value_type in a SFINAE context seems like a workable way to test if a type T is, in fact, an allocator.

    I don't think this is sufficient. This would just check if T has a value_type and is rebindable. Both libstdc++ and libc++ would consider std::map<int, int> to be an allocator in that model.

    The standard has a table of requirements for what constitutes an Allocator. I think your best bet would be just to check several of the expressions for validity, namely:

    • X::value_type
    • a.allocate(n) being valid and returning an X::pointer
    • a.deallocate(p, n) being valid

    (where X is the type you are checking, a is an X&, and n is a value of type allocator_traits<X>::size_type)

    If there's a type that checks all those boxes and still isn't an allcoator, well... ¯\_(ツ)_/¯.