chm*_*ike 37 c++ templates typedef c++11
我正在使用libgc,一个用于C和C++的垃圾收集器.要使STL容器可以收集垃圾,必须使用gc_allocator.
而不是写作
std::vector<MyType>
Run Code Online (Sandbox Code Playgroud)
一个人必须写
std::vector<MyType,gc_allocator<MyType> >
Run Code Online (Sandbox Code Playgroud)
可以有一种方法来定义类似的东西
template<class T> typedef std::vector<T,gc_allocator<T> > gc_vector<T>;
Run Code Online (Sandbox Code Playgroud)
我前一段时间检查过,发现它不可能.但我可能错了,或者可能有另一种方式.
以这种方式定义地图尤其令人不快.
std::map<Key,Val>
Run Code Online (Sandbox Code Playgroud)
变
std::map<Key,Val, std::less<Key>, gc_allocator< std::pair<const Key, Val> > >
Run Code Online (Sandbox Code Playgroud)
编辑:尝试使用宏后,我发现以下代码打破了它:
#define gc_vector(T) std::vector<T, gc_allocator<T> >
typedef gc_vector( std::pair< int, float > ) MyVector;
Run Code Online (Sandbox Code Playgroud)
模板化类型定义中的逗号被解释为宏参数分隔符.
所以内部类/结构似乎是最好的解决方案.
这是一个如何在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;
Run Code Online (Sandbox Code Playgroud)
Snp*_*nps 75
你可以使用using
像这样的C++ 11模板化类型别名
template <typename T>
using gc_vector = std::vector<T, gc_allocator<T>>;
Run Code Online (Sandbox Code Playgroud)
注意:我知道这是一个老问题,但由于它有很多赞成,因为它出现在搜索结果中,我认为它应该得到更新的答案.
Pao*_*sco 34
您不能使用"模板化typedef",但您可以使用具有内部类型的便捷类/结构:
template<typename T>
struct TypeHelper{
typedef std::vector<T,gc_allocator<T> > Vector;
};
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中使用
TypeHelper<MyType>::Vector v;
TypeHelper<MyType>::Vector::iterator it;
Run Code Online (Sandbox Code Playgroud)
和地图类似的东西:
template<typename K,typename V>
struct MapHelper{
typedef std::map<K, V, gc_allocator<K,V> > Map;
};
Run Code Online (Sandbox Code Playgroud)
编辑 - @Vijay:我不知道是否有另一种可能的解决方法,我就是这样做的; 一个宏可能会给你一个更紧凑的符号,但我个人不喜欢它:
#define GCVECTOR(T) std::vector<T,gc_allocator<T> >
Run Code Online (Sandbox Code Playgroud)
编辑- @chmike:请注意,该TypeHelper
解决方案不要求你重新定义构造函数!
你可以公开继承:
template<class T>
class gc_vector<T> : public std::vector<T, gc_allocator<T> >
{
public:
// You'll have to redeclare all std::vector's constructors here so that
// they just pass arguments to corresponding constructors of std::vector
};
Run Code Online (Sandbox Code Playgroud)
这完全解决了您的问题.派生类型可以在任何可以使用基类型的地方使用,并且没有任何合适的编译器的实现开销.
如果您尝试通过指向基类变量的指针删除派生类变量,则std :: vector具有非虚拟析构函数的事实可能会导致根据C++标准的未定义行为.
在现实世界中,这在这种特殊情况下无关紧要 - 与基类相比,派生类没有添加新内容,因此派生类的析构函数只调用基类的析构函数.无论如何都要小心翼翼地进行妄想.
如果您从未在堆上分配此类变量(并且通常在堆栈上分配矢量变量并作为其他类的成员),则非虚拟析构函数问题不会影响您.
归档时间: |
|
查看次数: |
23631 次 |
最近记录: |