2

iterator_typeに関連付けられたイテレータタイプに設定するには、YYY、ZZZに何を書き込む必要がありますTか?可能であれば、Visual Studio C ++ 2010で動作するはずです(ただし、一般的な標準ソリューションでも問題ありません)。

template<class T>
struct iterator_for {
    typedef YYY<T>::ZZZ type;
}

したがって、私は欲しい:

iterator_for<double[3]>::type is double *
iterator_for<std::string>::type is std::string::iterator
iterator_for<char[12]>::type is char *

Wrapper<T>反復可能なもの(つまり、コンテナー、文字列、または配列)を格納するテンプレートラッパークラスがあり、ラップされたオブジェクトを指す反復子を返す関数を定義したいと思います。そのためには、に対応するイテレータタイプについて話すことができる必要がありますT。配列の場合、対応するイテレータはポインタになり、文字列の場合は、そのイテレータタイプとして定義されている文字列になります。

4

4 に答える 4

4

コンテナをポインタから分離したいだけの場合は、これを試すことができます

template<class T>
struct iterator_for 
{
    typedef typename T::iterator  type;
};

template<class T>
struct iterator_for<T*>
{
    typedef T*  type;
};

template<class T, std::size_t N>
struct iterator_for<T (&)[N]>
{
    typedef T*  type;
};
于 2012-11-26T17:51:13.080 に答える
4

私の解決策は次のとおりです。

typedef decltype(std::begin(std::declval<T&>())) type;

イテレータ型は、std::beginのインスタンスで呼び出されたときに返される型ですTstd::declval<T&>を返すように宣言されておりT&、この上でを呼び出すことができますstd::begin

これは、コンテナタイプへの参照をに渡すという点でJohnBの回答とは異なりますstd::begin。これが必要な理由は次のとおりです。

  • std::declval<T>()右辺値参照(T&&)を返します。
  • std::begin非定数参照によって引数を取ります。
  • 非定数参照は一時的なものにバインドできません。

std::declval<T&>ただし、参照が折りたたまれているため、左辺値の参照を返します。

于 2017-06-20T19:58:43.327 に答える
3

わかりました。1つの可能性はおそらく(C ++ 11ではありますが、VS 2010では機能しません):

typedef typename std::remove_reference<
                    decltype ( 
                        begin ( std::declval<T> () )
                    )
                 >::type
        type;
于 2012-11-26T17:35:55.553 に答える
1

Boostライブラリにはすでにこれがあります:

#include <boost/range.hpp>
#include <iostream>
#include <string>
#include <vector>

template <typename T> void print_list(const T& container) {
    typedef typename boost::range_iterator<const T>::type iter;
    for (iter i = boost::begin(container); i != boost::end(container); ++i)
        std::cout << *i << ";";
    std::cout << "\n";
}

int main() {
    double array[] = {1.0,2.0,3.0};
    std::string str = "Hello";
    std::vector<int> vec(3, 10);
    print_list(array);  // prints 1;2;3;
    print_list(str);    // prints H;e;l;l;o;
    print_list(vec);    // prints 10;10;10;
}
于 2012-11-26T20:22:16.617 に答える