Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template typedef with std::vector to have custom allocator

I would like to define a custom vector class that uses std::vector class with custom allocator as below:

template <class T>
typedef std::vector<T, MyLib::MyAlloc<T> > my_vector;

Then, when I ttry to use it as:

  my_vector<std::string> v;

My g++ 2.95.3 Compiler on Solaris 10 complains stating that

 template declaration of `typedef class vector<T,MyLib::MyAlloc<T1> > my_vector'
aggregate `class my_vector<basic_string<char,string_char_traits<char>,__default_alloc_template<false,0> > > v' has incomplete type and cannot be initialized

Please help me to correct the snippet.

like image 469
Dr. Debasish Jana Avatar asked Jul 24 '26 08:07

Dr. Debasish Jana


1 Answers

C++11 supports this with the "new" type alias syntax:

template <class T>
using my_vector = std::vector<T, MyLib::MyAlloc<T> >;

The "old" form (typedef) cannot be used to create an alias template.


If C++11 or beyond is not an option. The only recourse is a template meta-function:

template <class T>
struct my_vector {
  typedef std::vector<T, MyLib::MyAlloc<T> > type;
};

Which can be used like this:

my_vector<std::string>::type v;

Or, since std::vector is a class type:

template <class T>
struct my_vector : std::vector<T, MyLib::MyAlloc<T> > {};

Which may be used as you originally wished it to be used.

like image 69
StoryTeller - Unslander Monica Avatar answered Jul 25 '26 20:07

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!