模板模板参数,不指定内部类型

Kon*_*app 18 c++ templates template-templates

我想知道是否有可能拥有具有以下行为的代码:

int main()
{
    func<vector>(/*some arguments*/);
}
Run Code Online (Sandbox Code Playgroud)

也就是说,我希望用户能够指定容器而不指定其操作的类型.

例如,可能定义的某些(元)代码(不适用于上述代码)func将如下所示:

template<typename ContainerType>
int func(/*some parameters*/)
{
    ContainerType<int> some_container;
    /*
        operate on some_container here
    */
    return find_value(some_container);
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*d42 22

语法是

template <template <typename...> class ContainerType>
int func(/*some parameters*/)
{
    // Your code with ContainerType<int>
}
Run Code Online (Sandbox Code Playgroud)

注意:class不能替换typename(直到c ++ 17).

你不能简单地使用typename而不是typename...因为std::vector 需要Type和Allocator(默认):std::vector<T, Allocator>

  • 从C++ 17`typename`就可以了. (5认同)

Mat*_* F. 9

试试这个:

template<template<typename,typename> class ContainerType>
int func (/*some parameters*/)
{

}
Run Code Online (Sandbox Code Playgroud)

您需要两个内部模板参数,因为std::vector它定义为:

template < class T, class Alloc = allocator<T> > class vector;