如何解释variadic模板中的继承

How to Interpret the Inheritance in Variadic Template?

本文关键字:继承 variadic 何解释 解释      更新时间:2023-10-16

我遇到了这篇文章:使用ConstexPr

将数字转换为字符串字面

答案很有趣:

namespace detail
{
    template<unsigned... digits>
    struct to_chars { static const char value[]; };
    template<unsigned... digits>
    const char to_chars<digits...>::value[] = {('0' + digits)..., 0};
    template<unsigned rem, unsigned... digits>
    struct explode : explode<rem / 10, rem % 10, digits...> {};
    template<unsigned... digits>
    struct explode<0, digits...> : to_chars<digits...> {};
}
template<unsigned num>
struct num_to_string : detail::explode<num> {};

我的问题是:

  1. " struct爆炸:爆炸"声明从爆炸中爆炸继承;那" struct爆炸&lt; 0,数字...>:to_chars"?

  2. '0'作为第一个模板参数的功能是什么?

谢谢!

这是一个具有部分专业化的递归公式,可作为终止条件。

explode<1234>

继承:

explode<123, 4>          // 1234 / 10 = 123, 1234 % 10 = 4

继承:

explode<12, 3, 4>        // 123 / 10 = 12, 123 % 10 = 3

继承:

explode<1, 2, 3, 4>      // 12 / 10 = 1, 12 % 10 = 2

继承:

explode<0, 1, 2, 3, 4>   // 1 / 10 = 0, 1 % 10 = 1

在这一点上,最左侧的值(在主模板中称为rem(是0,因此与部分专业化匹配:

template <unsigned... digits>
struct explode<0, digits...> : to_chars<digits...> {};

(指示整数变成单独的数字(,最终从:

继承。
to_chars<1, 2, 3, 4>

最后,to_chars将参数包扩展到char数组,也将数字转换为字符,因此1变为'1'2变为'2',等等:

const char to_chars<1, 2, 3, 4>::value[] = { '1', '2', '3', '4', 0 };

在这里, 0是null终止字符,因此value可以像字符串一样对待。