Search code examples
c++templatesc++11typedef

templated typedef?


I'm using libgc, a garbage collector for C and C++. To make STL containers garbage collectible one must use the gc_allocator.

Instead of writing

std::vector<MyType> 

one has to write

std::vector<MyType,gc_allocator<MyType> >

Could there be a way to define something like

template<class T> typedef std::vector<T,gc_allocator<T> > gc_vector<T>;

I checked some time ago and found out it was not possible. But I may have been wrong or there might be another way around.

Defining maps in this way is particularly unpleasing.

std::map<Key,Val> 

becomes

std::map<Key,Val, std::less<Key>, gc_allocator< std::pair<const Key, Val> > >

EDIT: After trying the use of macro I found out the following code breaks it:

#define gc_vector(T) std::vector<T, gc_allocator<T> >
typedef gc_vector( std::pair< int, float > ) MyVector;

The comma inside the templated type definition is interpreted as a macro argument separator.

So it seems the inner class/struct is the best solution.

Here is an example on how it will be done in C++0X

// standard vector using my allocator
template<class T>
using gc_vector = std::vector<T, gc_allocator<T> >;

// allocates elements using My_alloc
gc_vector <double> fib = { 1, 2, 3, 5, 8, 13 };

// verbose and fib are of the same type
vector<int, gc_vector <int>> verbose = fib; 

Solution

  • You can use C++11 templated type aliasing using using e.g. like this

    template <typename T>
    using gc_vector = std::vector<T, gc_allocator<T>>;