1

高度なC++の質問があります。std::allocatorテンプレートクラスのサブクラスであるmmap_allocatorテンプレートクラスと、std::vectorテンプレートクラスのサブクラスであるmmapable_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> {
            ...
    };

私にできることは、関数テンプレートを使用して、mmapable_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 :: vectorをmmappable_vectorsに変換する関数テンプレートを作成するにはどうすればよいですか?これはC++内でまったく可能ですか?

洞察をありがとう、

  • ヨハネス
4

1 に答える 1

2

mmappable_vector任意のタイプの 2 つのイテレータを取るテンプレート コンストラクタがありません。このように:

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 の 2 つの方法があります。

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 に答える