Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename std::vector to another class for overloading?

Look at this code.

#include <vector>

template<class ...Args>
using other_vector = std::vector<Args...>;

template<class T>
void f(std::vector<T>& ) {}
template<class T>
void f(other_vector<T>& ) {}

int main()
{
    other_vector<int> b;
    f(b);
    return 0;
}

It does not compile, because f is being redeclared. I totally understand the error. However, I need a second class that behaves like std::vector<T>, but will be seen as a different type, so that overloading, like in the above example, would be legal.

What could I do?

  • Let the new class have std::vector<T> as a base class. This might work, but one should not inherit from std containers.
  • Let the new class have a member of type std::vector and then redeclare all functions to redirect to the functions of the member. Sounds like a lot of work.

Any better alternative? C++11 or C++14 allowed.

like image 271
Johannes Avatar asked Jan 07 '14 13:01

Johannes


1 Answers

You might try to mess with the allocator:

template<class T>
struct allocator_wrapper : T { using T::T; };

template<class T, class A = std::allocator<T>>
using other_vector = std::vector<T, allocator_wrapper<A>>;

Live example

like image 97
Daniel Frey Avatar answered Nov 13 '22 07:11

Daniel Frey