Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

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.

Upvotes: 3

Views: 907

Answers (1)

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.

Upvotes: 2

Related Questions