0

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...

BigBrownBear00
  • 1,048
  • 1
  • 11
  • 19

4 Answers4

2

A simpler solution could be to implement your functions in terms of iterators, as is done in standard library algorithms:

template <typename Iterator>
void myFunction1(Iterator1 first, Iterator2 last) { .... }
juanchopanza
  • 210,243
  • 27
  • 363
  • 452
1

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;
    // ...
}
Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025
  • You shouldn't need to go to variadics. The library requirements say that there's a template named `vector` that takes two type arguments; while implementations are allowed to add extra arguments, they aren't allowed to make `vector` not work. The place where you can run into trouble is if you try to write your own declaration of a standard library type. Using a standard library type is simply required to work as documented. – Pete Becker Nov 15 '12 at 15:51
  • @PeteBecker: You're right. I was thinking of a different situation (specialization) where the "allowed extra arguments" come to bite you. Let me remove it from this post, though! – Kerrek SB Nov 15 '12 at 15:52
  • @PeteBecker: If you're curious, that's currently an open issue in the [pretty printer](http://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers): I want to provide specialized delimiters for sets, but I don't have a portable solution. – Kerrek SB Nov 15 '12 at 16:28
0

I think you have too change your template. But the good news is you can change your template to this:

template <typename MyVector> 
void myFunction1(MyVector& vin);
0x26res
  • 7,536
  • 9
  • 48
  • 90
0

You don't have to provide two overloads for each function template. Just provide the two-parameter one. std::vector has two template parameters, so both will be deduced just fine.

Angew is no longer proud of SO
  • 156,801
  • 13
  • 318
  • 412