模板typedef? [英] templated typedef?

查看:138
本文介绍了模板typedef?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用libgc,C和C ++的垃圾收集器。
为了使STL容器垃圾回收,必须使用gc_allocator。

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

而不是写

std::vector<MyType>

必须写

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>

成为

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

编辑:尝试使用宏后,我发现以下代码会破坏它:

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.

所以看起来内部类/ struct是最好的解决方案。

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

将在C ++ 0X中完成

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;


推荐答案

不能使用模板typedef可以使用具有内部类型的方便类/结构:

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;

地图类似:

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

EDIT - @Vijay:我不知道是否还有另一种可能的解决方法,它;一个宏可能给你一个更紧凑的符号,但个人我不喜欢它:

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:请注意 TypeHelper 解决方案要求您重新定义构造函数!

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

这篇关于模板typedef?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆