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>>;
注意:我知道这是一个老问题,但由于它有很多赞成票,而且当它出现在搜索结果中时,我认为它应该得到更新的答案.
这篇关于模板类型定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模板类型定义?
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
