How to avoid rebind in allocator<T, N> c++17

Viewed 1060

Before c++17, if you have an allocator like Allocator<typename, size_t> you can use the rebind struct. But now, in C++17 the rebind struct is deprecated. What's the solution to construct an allocator<T,size_t> from an allocator<T2, size_t>?

2 Answers

Only std::allocator's rebind member template is deprecated. If you are using your own class, you can still define rebind.

Do it through std::allocator_traits, like:

using AllocatorForU = std::allocator_traits<AllocatorForT>::template rebind_alloc<U>;

The default for rebind_alloc for AllocatorTemplate<T, OtherTypes...> is AllocatorTemplate<U, OtherTypes...>, which works for std::allocator, which is why std::allocator<T>::rebind is deprecated. You have to define it for your class since it has a non-type template parameter.

You might use std::allocator_traits:

std::allocator_traits<Alloc>::rebind_alloc<T>

with potential typename/template.

Related