2017-08-24 13 views
0

最初テンプレートテンプレートパラメータについて学習していましたが、intテンプレートをテンプレートから作成することができれば、vector<vector<int>>があるのか​​不思議に思っていました。テンプレートテンプレートパラメータの単純な例

しかし、例を作成しようとする過程で、私は単一レベルのテンプレートパラメータテンプレート関数を動作させることさえできません!

#include <iostream> 
#include <vector> 

template< 
    template<class> class C2, 
    class I 
> 
void for_2d(const C2<I>& container) 
{ 
    for(auto j : container){ 
     std::cout << j; 
    } 
} 

int main() { 
    std::vector<int> cont; 
    for_2d(cont); 
    return 0; 
} 

これが生成します。

17 : <source>:17:5: error: no matching function for call to 'for_2d' 
    for_2d(cont); 
    ^~~~~~ 
8 : <source>:8:6: note: candidate template ignored: substitution failure : template template argument has different template parameters than its corresponding template template parameter 
void for_2d(const C2<I>& container) 
    ^
1 error generated. 
Compiler exited with result code 1 
+0

はベクトルを試してみてください:: VALUE_TYPE -noそれを複雑にする必要があり、完全な実施例です。 – erenon

答えて

6

あなたが不足しているものは、(それらのほとんどは、デフォルト値を持っている)ベクトルは、複数のテンプレート引数を持っていることです。 あなたはこの

template< 
    template<class...> class C2, 
    class I 
> 
void for_2d(const C2<I>& container) 
{ 
    for(auto j : container){ 
     std::cout << j; 
    } 
} 

お知らせあなたの例ではコンパイルできない理由を説明バルトシュPrzybylskiのの答えのためのclass

0

+1後にドット、のためにあなたの関数を準備する必要がありますが、

をしたいですそう、あなたが auto j : containerを使用

そこからint型アウト

抽出あなたは(少なくとも)C++ 11を使用しています。ですから、私はあなたに、特定の再帰的な型特性の実装をお勧めします。

私はすべての以下firtType まず、一般的な(専門ではない)のバージョン(つまり再帰端子で)提案

template <typename T> 
struct firstType 
{ using type = T; }; 

次にseguenceを受信std::vectorおよび他のコンテナ同様のコンテナ(そのための専門

template <template <typename...> class C, typename T0, typename ... Ts> 
struct firstType<C<T0, Ts...>> 
{ using type = typename firstType<T0>::type; }; 

)タイプのこの特殊化はタイプと番号を受け取るstd::array、とコンテナの多くではなく、で動作します。以下は、その他の特殊化が要求されてもよいstd::array

template <template <typename, std::size_t> class C, typename T, std::size_t N> 
struct firstType<C<T, N>> 
{ using type = typename firstType<T>::type; }; 

ための特殊です。

次は

#include <array> 
#include <vector> 
#include <type_traits> 

template <typename T> 
struct firstType 
{ using type = T; }; 

template <template <typename...> class C, typename T0, typename ... Ts> 
struct firstType<C<T0, Ts...>> 
{ using type = typename firstType<T0>::type; }; 

template <template <typename, std::size_t> class C, typename T, std::size_t N> 
struct firstType<C<T, N>> 
{ using type = typename firstType<T>::type; }; 

int main() 
{ 
    std::vector<int>     vi; 
    std::array<long, 42U>   al; 
    std::vector<std::vector<short>> vvs; 

    static_assert(std::is_same<typename firstType<decltype(vi)>::type, 
           int>::value, "!"); 
    static_assert(std::is_same<typename firstType<decltype(al)>::type, 
           long>::value, "!"); 
    static_assert(std::is_same<typename firstType<decltype(vvs)>::type, 
           short>::value, "!"); 
}