如何指定模板参数是 class 模板,并从另一个模板参数推断其模板类型?
How to specify that template parameter is a class template, and infer its template type from another template parameter?
考虑一个模板函数:
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
作为参数以避免复制输入容器。
考虑一个模板函数:
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
作为参数以避免复制输入容器。