我有一个高级C 问题:假设我有一个mmap_allocator模板类是STD ::分配器模板的子类类和mmappable_vector模板类是一个子类STD :: vector模板类:
template <typename T>
class mmap_allocator: public std::allocator<T> {
...
};
template <typename T, typename A = mmap_allocator<T> >
class mmappable_vector: public std::vector<T, A> {
...
};
我能做的就是从mmappable_vector转换(使用mmap_allocator)使用功能模板到STD :: vector(带有标准分配器):
template <typename T>
std::vector<T> to_std_vector(const mmappable_vector<T> &v)
{
return std::vector<T>(v.begin(), v.end());
}
,但另一种方式似乎是不可能的:
template <typename T>
mmappable_vector<T> to_mmappable_vector(const std::vector<T> &v)
{
return mmappable_vector<T>(v.begin(), v.end());
}
定义构造函数时的问题:
typedef typename std::vector<T, A>::iterator iterator;
mmappable_vector(iterator from, iterator to):
std::vector<T,A>(from, to)
{
}
这将迭代器与MMAP_Allocator一起使用,因此不匹配呼叫to_mmappable_vector。另一方面定义构造函数:
mmappable_vector(std::vector<T,std::allocator<T> > v):
std::vector<T,std::allocator<T> >(v)
{
}
失败,因为
std::vector<T,std::allocator<T> >
不是Mmappable向量的基类。
如何编写一个将std ::向量转换为vectors的函数模板mmappable_vectors?在C ?
中,这是否可以感谢您的任何见解,
- 约翰内斯
您在mmappable_vector
中没有模板构造函数,该模板构造器需要任何类型的两个迭代器。像这样:
template <typename T, typename A = mmap_allocator<T> >
class mmappable_vector: public std::vector<T, A> {
typedef std::vector<T, A> Base;
...
template <typename Iter>
mmappable_vector(Iter first, Iter last, A a = A()) : Base(begin, end, a) {}
};
请参阅http://www.sgi.com/tech/stl/stl_vector.h
,但更重要的是,您不应该完全定义您的向量:
template <typename T, typename A = mmap_allocator<T> >
class mmappable_vector: public std::vector<T, A> {
...
};
这是错误的,因为它源自STL容器,推导是公开的,并且您没有虚拟破坏者。
据我了解您的问题 - 您只需要一个Typedef即可。在C -C 11和C 03中制作Typedef的方法有两种:
C 11
template< typename T, typename A = mmap_allocator<T> >
using mmappable_vector = std::vector<T, A>;
C 03
template <typename T, typename A = mmap_allocator<T> >
struct mmappable_vector {
typedef std::vector<T, A> type;
};
使用它为:
mmappable_vector<int>::type