开发者社区> 问答> 正文

更改变量模板中的最后一个类型

实际上,我发现了类似的问题,但都与函数参数包有关,并通过std::tuple和std::index_sequence...我需要一些不同的东西,而我自己也无法建立联系。下面是:

假设我有一个函数,带着一些变量包,我想实现:

template <typename NewVal, template Container, typename T, typename... Ts>
auto foo(Container<T, Ts...> t, NewVal const& v) {
    using OutContainer= Container<NewVal, Same as Ts up to last Type..., but LastElement should be different>
    OutContainer o;
    // fill this new container with v
    return o;
}

我观察到,在STL,Allocator容器中的模板参数总是最后一个,存储的类型总是第一个(不要介意)std::map现在)。所以,如果我想Container 变成Container ,我还需要处理最后一个分配器参数,以便在这个新类型中使用一个分配器。有什么想法吗?

当然,这是一种伪码,Container是模板-模板参数。

展开
收起
aqal5zs3gkqgc 2019-12-19 20:59:17 3105 0
1 条回答
写回答
取消 提交回答
  • 喂食js std::make_index_sequence<N>或std::index_sequence_for<Ts...> 对
    于助手来说,结构或函数通常是对包进行非琐碎操作的最简单方法。

    要使用所需的类型转换创建一个帮助器结构,首先使用必要的输入声明它,再加上一个额外的类型参数以接受```js std::index_sequence:

    namespace foo_detail { template <template <typename...> class Container, typename NewFirstT, typename NewLastT, typename IdxSeq, typename ... Tail> struct OutContainerHelper; }

    然后进行部分专门化,可以使用任何```js
    std::index_sequence<I...>:
    
    
    namespace foo_detail
    {
        template <template <typename...> class Container,
                  typename NewFirstT,
                  typename NewLastT,
                  std::size_t ... I,
                  typename ... Tail>
        struct OutContainerHelper<
            Container, NewFirstT, NewLastT, std::index_sequence<I...>, Tail...>
        {
            using type = Container<
                NewFirstT,
                std::conditional_t<(I+1 == sizeof...(Tail)), NewLastT, Tail>...
            >;
        };
    }
    
    

    那就提供一个js std::make_index_sequence或std::index_sequence_for 作
    为帮助程序的模板参数:

    template <template <typename...> class Container,
              typename OldFirstT,
              typename T2,
              typename... Ts,
              typename NewVal>
    auto foo(Container<OldFirstT, T2, Ts...> t, NewVal const& v) {
        using NewLastT = ???;
        using OutContainer = typename foo_detail::OutContainerHelper<
            Container, NewVal, NewLastT,
            std::index_sequence_for<T2, Ts...>, T2, Ts...
        >::type;
        OutContainer o;
        // fill this new container with v
        return o;
    }
    
    

    (追加T2确保Container专门化至少有两个模板参数,因为转换没有意义。如果有人尝试将编译错误与一个只有一个模板参数的模板一起使用,那么编译错误可能会减少一些混乱。)

    关于Coliru的工作实例。

    2019-12-19 21:01:09
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载