模板类型定义?

2023-03-09C/C++开发问题
2

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

问题描述

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

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

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6