如何指定模板参数是类模板,并从另一个模板参数推断其模板类型? [英] How to specify that template parameter is a class template, and infer its template type from another template parameter?

查看:181
本文介绍了如何指定模板参数是类模板,并从另一个模板参数推断其模板类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个模板函数:

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

我可以这样说没有问题:

I can call it no problem like so:

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

。所以必须指定 std :: set< MyClass>> 是多余的;我想键入 processContainer< std :: set>(v)并且具有推断项类型为 decltype(v):: value_type 。我该怎么办?我尝试过不同的事情,如

However, I know that the function will accept and produce different containers, but always with the same element type. So having to specify std::set<MyClass>> is redundant; I want to type processContainer<std::set>(v) and have the function infer the item type as decltype(v)::value_type. How can I do that? I've tried different things like

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

但不能让它编译无论什么的C ++模板语法和技巧不是很深,如你所见)。

but can't get it to compile no matter what (my understanding of C++ template syntax and tricks is not very deep, as you can see).

推荐答案

如果你不在乎分配器,您可以忽略它:

If you don't care about the allocator, you can just omit it:

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

DEMO

这篇关于如何指定模板参数是类模板,并从另一个模板参数推断其模板类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆