模板类型定义? [英] templated typedef?

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

问题描述

我正在使用 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.

所以看起来内部类/结构是最好的解决方案.

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; 

推荐答案

您可以使用 C++11 模板化类型别名使用 using 例如像这样

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

注意:我知道这是一个老问题,但由于它有很多赞成票,而且当它出现在搜索结果中时,我认为它应该得到更新的答案.

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

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