可变模板类型演绎

Variadic templates type deduction

本文关键字:类型 演绎      更新时间:2023-10-16

我看到了一篇很棒的文章:http://pdimov.com/cpp2/simple_cxx11_metaprogramming.html

在以下代码中:

template<class A, template<class...> class B> struct mp_rename_impl;
template<template<class...> class C, class... T, template<class...> class B>
struct mp_rename_impl<C<T...>, B>
{
    using type = B<T...>;
};
template<class A, template<class...> class B>
using mp_rename = typename mp_rename_impl<A, B>::type;
//...
mp_rename<mp_list<int, float, void*>, std::tuple>; // -> std::tuple<int, float, void*>
                                                   // T... will be deduced as int, float, void*

为什么C被演绎为mp_list(而不是mp_list<int,>)和T…作为int, float, void* ?

我认为诀窍在于模板特化部分: struct mp_rename_impl, B>,但我很难理解为什么

with

mp_rename<mp_list<int, float, void*>, std::tuple>;
  • template<class A, template<class...> class B>
    using mp_rename = typename mp_rename_impl<A, B>::type;
    

    Amp_list<int, float, void*>, Bstd::tuple

  •  template<class A, template<class...> class B> struct mp_rename_impl;
    

    A = mp_list<int, float, void*>, B = std::tuple

  • 专门化

    template<template<class...> class C, class... Ts, template<class...> class B>
    struct mp_rename_impl<C<Ts...>, B>
    

    (我重命名为C更清楚)
    Cmp_list, Ts...int, float, void*, Bstd::tuple