模板模板参数简单示例

Ste*_* Lu 0 c++ templates type-traits template-templates c++11

首先,我正在学习模板模板参数,我开始想知道我是否有一个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;
}
Run Code Online (Sandbox Code Playgroud)

这会产生:

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
Run Code Online (Sandbox Code Playgroud)

小智 6

你缺少的是vector有多个模板参数(大多数都有默认值).你需要为此准备你的功能

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

注意后面的点 class