0

Given the following function signature

void foo(std::vector<int> &bar);

and a custom allocator CustomAlloc, calling foo with a instance of std::vector<int, CustomAlloc> results in

could not convert ‘bar’ from ‘std::vector<int, CustomAlloc<int, [...] >}’ to ‘std::vector<int>’

I am no C++ template guru and please do correct me if I am wrong but my understanding is that std::vector<int> default to std::vector<int, std::allocator<int> > (gcc 7.1.1.-3) and hence defines a completely unrellated type.


This beeing said I am trying to find some solutions to make foo callable using std::vector<int, CustomAlloc> and came with the following.

template<typename Allocator>
void foo(std::vector<int, Allocator> &bar);

I dislike how the allocator specification propagates templates, but I guess that is how the STL works.

So my question is, how would you solve this problem given that foo specically operates on int?

PS: Apologies for the bad title I just couldn't find a good one

dna
  • 1,085
  • 7
  • 15
  • It's not clear if you need `foo` to take different types of parameters, but if the requirement is to use `CustomAlloc` only, you can declare it `void foo(std::vector &bar);` without any templates. – Bo Persson Jun 30 '17 at 11:03

1 Answers1

2

There is an entirely new namespace in the standard for solving this issue - namespace pmr. See polymorphic_allocator: when and why should I use it?

As to what you can do to avoid the propagation of this issue with templates without the pmr solution. The answer is you can't, you need to either hard specify the allocator parameter, or you need to template the vector to accept any type of allocator.

Curious
  • 20,870
  • 8
  • 61
  • 146
  • 1
    Thanks, this looks promising and proposes an elegant solution to this problem. – dna Jun 30 '17 at 11:12