【发布时间】:2012-10-17 14:32:08
【问题描述】:
我有一个高级 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++ 中是否可行?
感谢您的任何见解,
- 约翰内斯
【问题讨论】:
-
查找带有一对迭代器的向量构造函数。它不需要 vector::iterators,它需要 any 个迭代器。
标签: c++ templates constructor subclassing allocator