如何解释Variadic模板中的继承?

Hei*_*Hei 2 c++ c++11

我遇到过这篇文章: 使用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> {};
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. "struct explode:explode"声明爆炸继承自爆炸; 怎么样"struct explode <0,digits ...>:to_chars"?

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

谢谢!

Pio*_*cki 6

这是一个递归公式,具有部分特化作为终止条件.

explode<1234>
Run Code Online (Sandbox Code Playgroud)

继承自:

explode<123, 4>          // 1234 / 10 = 123, 1234 % 10 = 4
Run Code Online (Sandbox Code Playgroud)

继承自:

explode<12, 3, 4>        // 123 / 10 = 12, 123 % 10 = 3
Run Code Online (Sandbox Code Playgroud)

继承自:

explode<1, 2, 3, 4>      // 12 / 10 = 1, 12 % 10 = 2
Run Code Online (Sandbox Code Playgroud)

继承自:

explode<0, 1, 2, 3, 4>   // 1 / 10 = 0, 1 % 10 = 1
Run Code Online (Sandbox Code Playgroud)

此时,最左侧的值(rem在主模板中称为)0,因此它与部分特化匹配:

template <unsigned... digits>
struct explode<0, digits...> : to_chars<digits...> {};
Run Code Online (Sandbox Code Playgroud)

(表示整个数字变成了单独的数字),最终继承自:

to_chars<1, 2, 3, 4>
Run Code Online (Sandbox Code Playgroud)

最后,to_chars将参数包扩展为一个char数组,同时将数字转换为字符,以便1变为'1',2变成'2'等等:

const char to_chars<1, 2, 3, 4>::value[] = { '1', '2', '3', '4', 0 };
Run Code Online (Sandbox Code Playgroud)

这里0是null终止字符,因此value可以将其视为字符串.