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

Template template parameters without specifying inner type

本文关键字:参数 类型 内部      更新时间:2023-10-16

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

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);
}

语法是

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

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

您不能简单地使用 typename 而不是 typename... 因为std::vector 采用类型和分配器(默认):std::vector<T, Allocator>

试试这个:

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

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

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