Question

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; 
 45  36995  45
1 Jan 1970

Solution

 99

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

Solution

 37

You cannot use a "templated typedef", but you can use a convenience class/struct with an inner type:

template<typename T>
struct TypeHelper{
    typedef std::vector<T,gc_allocator<T> > Vector;
};

and then use in your code

TypeHelper<MyType>::Vector v;
TypeHelper<MyType>::Vector::iterator it;

And something similar for the map:

template<typename K,typename V>
struct MapHelper{
    typedef std::map<K, V, gc_allocator<K,V> > Map;
};

EDIT - @Vijay: I don't know if there's another possible workaround, that's how I would do it; a macro might give you a more compact notation, but personally I wouldn't like it:

#define GCVECTOR(T) std::vector<T,gc_allocator<T> >

EDIT - @chmike: Please note that the TypeHelper solution does not require you to redefine constructors!

2009-03-16