Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;  
like image 238
chmike Avatar asked Mar 16 '09 09:03

chmike


People also ask

What is a typedef in C++?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

What is typedef Typename?

typedef is defining a new type for use in your code, like a shorthand. typedef typename _MyBase::value_type value_type; value_type v; //use v. typename here is letting the compiler know that value_type is a type and not a static member of _MyBase . the :: is the scope of the type.


1 Answers

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

Note: I know this is an old question but since it has quite many upvotes and as it turns up in search results I thought it deserved an updated answer.

like image 101
Felix Glas Avatar answered Sep 28 '22 02:09

Felix Glas