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
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
