2017-08-24 144 views
0

首先我學習了模板模板參數,我開始想知道如果我有一個vector<vector<int>>,如果我可以製作一個模板,從那裏抽取出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 - 沒有需要把它複雜化。 – erenon

回答

6

你缺少的事情是,向量有多個模板參數(大部分有默認值)。 你需要後class

0

+1的巴爾託什Przybylski的答案,這解釋了爲什麼你的例子不能編譯準備你的函數這個

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

注意點,但你要

提取出類型爲int從那裏

您使用auto j : container,所以你正在使用(至少)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, "!"); 
}