1

我有一个高级 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++ 中可能吗?

感谢您的任何见解,

  • 约翰内斯
4

1 回答 1

2

您没有模板构造函数,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++ 中制作 typedef 有两种方法 - C++11 和 C++03 方式:

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
于 2012-10-17T14:35:34.137 回答