gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:09:22 25 4
gpt4 key购买 nike

我看到这篇文章: Convert a number to a string literal with 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 explode : explode”声明explode继承自explode; “struct explode<0, digits...> : 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 是空终止字符,因此可以将 value 视为字符串。

关于c++ - 如何解释 Variadic 模板中的继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43629263/

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