1

I wish to pass an allocator type to a class, without needing the client to specify the types of its members.

For example:

#include <string>
#include <memory>
#include <vector>

template<typename STRALLOC, typename INTALLOC>
struct Thing {
    std::vector<std::string, STRALLOC> string_content;
    std::vector<int,         INTALLOC> int_content;
};

int main() {
    Thing<std::allocator<std::string>, std::allocator<int>> heapStuff;
    Thing<std::pmr::polymorphic_allocator<std::string>, std::pmr::polymorphic_allocator<int>> polyStuff;
    return 0;
}

I would like to be able to simply use something like the following:

template<typename ALLOC>
struct Thing {
    std::vector<std::string, ALLOC<std::string> string_content;
    std::vector<int,         ALLOC<int> int_content;
};

int main() {
    Thing<std::allocator> heapStuff;
    Thing<std::pmr::polymorphic_allocator> polyStuff;
    return 0;
}

However I cannot do this because e.g. std::allocator is not a typename without its template parameter.

Is there any wizardry to make this possible?

[edit]

This actually appears to be simple:

#include <string>
#include <memory>
#include <vector>

template<template<class> typename ALLOCATOR>
struct Thing {
    std::vector<std::string, ALLOCATOR<std::string>> string_content;
    std::vector<int,         ALLOCATOR<int>> int_content;
};

int main() {
    Thing<std::allocator> heapStuff;
    Thing<std::pmr::polymorphic_allocator> polyStuff;
    return 0;
}
Den-Jason
  • 2,395
  • 1
  • 22
  • 17

0 Answers0