Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

c++ - 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; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...