如何指定模板参数是类模板,并从另一个模板参数推断其模板类型
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
以避免复制输入容器。
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如果需要转换,我可以在读取参数的同时将其移动到另一个参数吗?
- 如何在另一个函数中使用返回值作为参数?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 如何使用另一个类中的公共成员函数作为参数调用线程
- 如何将 lambda 函数作为参数发送到另一个函数
- 将可变参数从一个函数传递到另一个函数
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 将一个宏传递到另一个宏而不是直接传递内容时会出现不需要的额外"空"参数
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 如何设置默认参数以防用户不输入另一个参数
- C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- 将另一个类的成员函数传递到 std::function 参数中
- 如何参数化用作另一个 lambda 参数的 lambda
- 将参数从一个函数传递到另一个函数(没有模板) - C++
- 重构模板类,该类将其嵌套类用作另一个类的模板参数