如何指定模板参数是类模板,并从另一个模板参数推断其模板类型

How to specify that template parameter is a class template, and infer its template type from another template parameter?

本文关键字:参数 另一个 类型 何指定      更新时间:2023-10-16

考虑一个模板函数:

template <typename OutputContainerType, typename ContainerType>
static OutputContainerType processContainer(ContainerType c)
{
    OutputContainerType result;
    ...
    return result;
}

我可以这样称呼它没有问题:

std::vector<MyClass> v;
const auto result = processContainer<std::set<MyClass>>(v);

但是,我知道该函数将接受并生成不同的容器,但始终具有相同的元素类型。因此,必须指定std::set<MyClass>>是多余的;我想键入processContainer<std::set>(v)并让函数推断项目类型为 decltype(v)::value_type .我该怎么做?我尝试过不同的事情,例如

template <template<> class OutputContainerType, class ContainerType>
static OutputContainerType<typename ContainerType::value_type> processContainer(ContainerType c) {}

但无论如何都无法让它编译(如您所见,我对C++模板语法和技巧的理解不是很深入)。

如果你不关心分配器,你可以省略它:

template <template<typename...> class OutputContainerType, template<typename...> class ContainerType, typename ValueType>
static OutputContainerType<ValueType> processContainer(ContainerType<ValueType> c)
{
    OutputContainerType<ValueType> result;
    //  ...
    return result;
}
int main() {
    std::set<int> s {1, 2, 3};
    auto v = processContainer<std::vector, std::set, int>(s);
}

演示

您可以使用

template<template<typename...> class OutputContainerType,
         typename InputContainerType>
static OutputContainerType<typename InputContainerType::value_type>
processContainer(InputContainerType c)
{
    using ValueType = typename InputContainerType::value_type;
    OutputContainerType<ValueType> result;
    //  ...
    return result;
}

还可以考虑对参数使用 const InputContainerType& c以避免复制输入容器。

相关文章: