gpt4 book ai didi

c++ - 给定一个任意容器,推导出一个相关类型的容器类型

转载 作者:行者123 更新时间:2023-12-04 11:54:41 24 4
gpt4 key购买 nike

假设我有一个模板类 Wrapper , 有没有办法创建一个类型别名模板,自动推导出 Wrapper <T> 的容器来自 T 的容器, 以便:

  • alias(Wrapper, vector<int>)会变成vector<Wrapper<int>>
  • alias(Wrapper, map<int, string>)会变成map<Wrapper<int>, Wrapper<string>>
  • alias(Wrapper, array<int, 10>)会变成array<Wrapper<int>, 10>

  • 到目前为止,我所做的最好的尝试是:
    template<template<typename> typename U, template<typename...> typename Container, typename ...T>
    using alias = std::remove_cvref_t<decltype(std::declval<Container<U<T>...>>())>;
    但是有两个问题:
  • 它必须使用如下语法调用:此版本需要调用类似(这并不理想):alias(vector, Type)alias(map, Key, Value) .我很想使用 alias(vector<Type>)alias(map<Key, Value>)如果可能的话。
  • 它与 std::array 不兼容因为 array 的第二个模板参数是 size_t不是一种类型。我想我可以创建第二个类型别名并根据容器类型调用相应的别名,但我不想这样做。
  • 最佳答案

    不确定这是否正是您所需要的,但是类模板的特化可以很好地处理这个问题:

    #include <type_traits>
    #include <vector>
    #include <array>
    #include <map>
    #include <string>

    template<template<typename> typename Wrapper, typename Container>
    struct repack;

    template<template<typename> typename Wrapper, typename ValueT>
    struct repack<Wrapper, std::vector<ValueT>>
    {
    using type = std::vector<Wrapper<ValueT>>;
    };

    template<template<typename> typename Wrapper, typename ValueT, std::size_t N>
    struct repack<Wrapper, std::array<ValueT, N>>
    {
    using type = std::array<Wrapper<ValueT>, N>;
    };

    template<template<typename> typename Wrapper, typename Key, typename Value>
    struct repack<Wrapper, std::map<Key, Value>>
    {
    using type = std::map<Wrapper<Key>, Wrapper<Value>>;
    };

    template<template<typename> typename Wrapper, typename Container>
    using repack_t = typename repack<Wrapper, Container>::type;
    https://godbolt.org/z/naz9v48vb
    它通过了您指定的测试。

    关于c++ - 给定一个任意容器,推导出一个相关类型的容器类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69436122/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com