我有一个高级 C++ 问题:假设我有一个 mmap_allocator 模板类,它是 std::allocator 模板类的子类和一个 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++ 中可能吗?
感谢您的任何见解,
- 约翰内斯