Rename std :: vector to another class for overloading?

Take a 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 updated. I fully understand the error. However, I need a second class that behaves like std::vector<T> , but will be treated as a different type, so that overloading, as in the above example, would be legal.

What can I do?

  • Let the new class have std::vector<T> as the base class. This may work, but does not need to inherit from std containers.
  • Suppose a new class has a member of type std :: vector, and then overrides all functions to redirect to member functions. Sounds like a lot of work.

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

+6
source share
3 answers

You can try to get confused with the dispenser:

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

Living example

+17
source

If you need more than one copy, you can make it a template and take the int template argument for the "number of clones"

0
source

You can wrap your type as follows:

 // N allow to have several 'version' of the same type T template <typename T, int N = 0> class WrapperType { public: WrapperType() = default; WrapperType(const WrapperType&) = default; WrapperType(WrapperType&&) = default; template <typename ... Ts> explicit WrapperType(Ts&& ... ts) : t(std::forward<Ts>(ts)...) {} // implicit conversion // you may prefer make them explicit or use name get(). operator const T& () const { return t; } operator T& () { return t; } private: T t; }; 

And so for your case:

 template<class T> using other_vector = WrapperType<std::vector<T>>; 
0
source

All Articles