Search code examples
c++templatesallocator

Template functions with STL Vectors break with new allocator


I have a ton of functions that are defined as something like:

template<typename T>
void myFunction1(vector<T>& vin);

The point being, I input an STL vector and do some work.

I have recently needed to change the default allocator to a customer allocator. This seems to break every function unless I change the definitions to:

template<typename T, typename Alloc>
void myFunction1(vector<T,Alloc>& vin);

To make it more complicated, I will not be using the overloaded allocator in all cases..

Does this mean I have to rewrite EVERY function with two definitions, one with the template for the allocator and the other definition without the allocator? I really hope this isn't the answer...


Solution

  • It's entirely adequate to have one single function template that respects the full class template. Hypothetically, this will do:

    template <typename T, typename Alloc>
    void myFunction1(std::vector<T, Alloc> & v);
    

    Every vector has those two arguments, no matter whether the allocator one is defaulted or not.

    However, a more fruitful idiom is actually to make the entire container a template:

    template <typename V>
    void myFunction1(V & v)
    {
        typedef typename V::value_type value_type;
        // ...
    }