templated 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.
所以看起来内部类/结构是最好的解决方案.
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>>;
注意:我知道这是一个老问题,但由于它有很多赞成票,而且当它出现在搜索结果中时,我认为它应该得到更新的答案.
这篇关于模板类型定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模板类型定义?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
