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

时间:2016-07-05 10:22:11

标签: c++ templates template-templates

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

int main()
{
    func<vector>(/*some arguments*/);
}

也就是说,我希望用户能够在不指定其操作类型的情况下指定容器。

例如,可能定义func的某些(元)代码(不能与上述代码一起使用)如下:

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

2 个答案:

答案 0 :(得分:22)

语法是

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

注意:class不能被typename取代(直到c ++ 17)。

您不能简单地使用typename代替typename...,因为std::vector  采用Type和Allocator(默认):std::vector<T, Allocator>

答案 1 :(得分:9)

试试这个:

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

}

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

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