对C++中模板参数包的类型的部分提取

本文最后更新于:2024年2月12日 下午

  • 首先我们需要一个辅助类,用以传递类型本身

    1
    2
    3
    template <typename ...Types>
    class typePass
    {};
  • 之后,我们定义一个类,用以捕获模板参数包中的部分参数,再用模板函数的自动推导补全剩余的类型

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    template <typename ...PartTypes>
    class extractor
    {
    template <typename ...AnotherPartTypes>
    static auto extractBack(typePass<PartTypes..., AnotherPartTypes...>)
    {
    return typePass<AnotherPartTypes...>;
    };
    template <typename ...AnotherPartTypes>
    static auto extractFront(typePass<AnotherPartTypes..., PartTypes...>)
    {
    return typePass<AnotherPartTypes...>;
    };
    };
  • 使用方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    #include <functional>
    #include <tuple>
    #include <any>

    // 函数包装
    std::function<void(std::any&&)> wrapper;

    // 赋值函数包装的实际函数
    template <typename ...Args, typename ...PreArgs, typename ...PostArgs, typename ...PostIndex>
    void setWrapperE(const std::function<void(Args...)> &func, typePass<PostArgs...>, std::index_sequence<PostIndex...>, PreArgs&& ...pre)
    {
    wrapper = [](std::any &&postTuple){
    auto post = std::any_cast<std::tuple<PostArgs...>>(postTuple);
    func(pre..., std::get<PostIndex>(post)...);
    };
    }

    // 赋值函数包装的外层包装
    template <typename ...Args, typename ...PreArgs>
    void setWrapper(const std::function<void(Args...)> &func, PreArgs&& ...pre)
    {
    setWrapperE(func, extract<PreArgs...>::extractBack(typePass<Args...>()), std::make_index_sequence<sizeof...(PreArgs)>(), pre...);
    }

    // 调用函数包装
    template <typename ...PostArgs>
    void runWrapper(PostArgs&& ...post)
    {
    wrapper(std::any(std::tuple(post...)));
    }

对C++中模板参数包的类型的部分提取
https://www.12hydrogen.dev/2024/02/12/Extract-Part-Of-Template-Package/
作者
12Hydrogen
发布于
2024年2月12日
更新于
2024年2月12日
许可协议