Skip to content

Instantly share code, notes, and snippets.

@grisumbras
Created June 27, 2019 06:13
Show Gist options
  • Select an option

  • Save grisumbras/13a249d62c5c29a38191a4f13fe6f776 to your computer and use it in GitHub Desktop.

Select an option

Save grisumbras/13a249d62c5c29a38191a4f13fe6f776 to your computer and use it in GitHub Desktop.

Revisions

  1. grisumbras created this gist Jun 27, 2019.
    28 changes: 28 additions & 0 deletions vector_alloc_prop.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    template <class Vector, class ProtoAllocator>
    auto require(Vector &&vec, std::execution::allocator_t<Allocator> prop) {
    using V = std::decay_t<Vector>;
    using SourceAllocator = typename V::allocator_type;
    using ValueType = typename V::value_type;

    using ProtoTraits = std::allocator_traits<ProtoAllocator>;
    using TargetAllocator =
    typename ProtoTraits::template rebind_alloc<ValueType>;

    TargetAllocator const target_alloc = prop.value();
    if constexpr (std::is_same_v<SourceAllocator, TargetAllocator>) {
    if (vec.get_allocator() == target_alloc) {
    return vec;
    } else {
    return V(vec.begin(), vec.end(), target_alloc);
    }
    } else {
    return std::vector<ValueType, TargetAllocator>(vec.begin(), vec.end(),
    target_alloc);
    }
    }

    template <class Vector, class ProtoAllocator>
    auto switch_allocator_for_vector(Vector &&vec, ProtoAllocator alloc) {
    return std::require(std::forward<Vector>(vec),
    std::execution::allocator(alloc));
    }