如何解释variadic模板中的继承
How to Interpret the Inheritance in Variadic Template?
我遇到了这篇文章:使用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> {};
我的问题是:
" struct爆炸:爆炸"声明从爆炸中爆炸继承;那" struct爆炸&lt; 0,数字...>:to_chars"?
'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
可以像字符串一样对待。
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- Variadic模板未编译
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- variadic模板中的模板参数推导失败
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 如何解释variadic模板中的继承
- variadic模板扩展,继承和std :: unique_ptr
- 带有递归继承和使用声明的Variadic模板
- 用类型的递归继承获得Variadic模板的阴影成员