本文介绍了阶乘 T - 1 的含义在模板定义中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我很难理解以下模板定义和模板特化定义是如何工作的?对我来说,factorial 或 factorial 看起来很奇怪!例如:factorial::value什么意思?#include 模板结构阶乘{enum { value = factorial::value * T };};模板<>结构阶乘 1{枚举 { 值 = 1 };};int main(){std::cout <<阶乘::值 解决方案 这是模板元编程的示例.该程序在编译时使用递归计算阶乘.递归的基础在这里:模板结构阶乘 1{枚举 { 值 = 1 };};它说 1 的阶乘是 1.另一个模板简单地说,一个数的阶乘是这个数乘以阶乘减 1.template结构阶乘{enum { value = factorial::value * T };};由于真的没有经典意义上的调用",模板实例化自身,模板参数等于编译时计算的 T-1.>附言警告显示 34 的阶乘溢出 32 位整数.I have difficulties to understand how the following template definition and template specialization definition work? To me, factorial<34> or factorial<T-1> look strange!For example:factorial<T - 1>::valuemeans what?#include <iostream>template<int T>struct factorial { enum { value = factorial<T - 1>::value * T };};template<>struct factorial<1> { enum { value = 1 };};int main(){ std::cout << factorial<34>::value << std::endl;}g++ -o testSTL01 testSTL01.cpp -WalltestSTL01.cpp: In instantiation of ‘factorial<13>’:testSTL01.cpp:5:3: instantiated from ‘factorial<14>’testSTL01.cpp:5:3: instantiated from ‘factorial<15>’testSTL01.cpp:5:3: instantiated from ‘factorial<16>’testSTL01.cpp:5:3: instantiated from ‘factorial<17>’testSTL01.cpp:5:3: instantiated from ‘factorial<18>’testSTL01.cpp:5:3: [ skipping 11 instantiation contexts ]testSTL01.cpp:5:3: instantiated from ‘factorial<30>’testSTL01.cpp:5:3: instantiated from ‘factorial<31>’testSTL01.cpp:5:3: instantiated from ‘factorial<32>’testSTL01.cpp:5:3: instantiated from ‘factorial<33>’testSTL01.cpp:5:3: instantiated from ‘factorial<34>’testSTL01.cpp:15:29: instantiated from heretestSTL01.cpp:5:3: warning: integer overflow in expressionstart to run the app ...0 解决方案 This is an example of template metaprogramming. This program calculates factorial at compile time using recursion. The base of recursion is here:template<>struct factorial<1> { enum { value = 1 };};It says that factorial of 1 is 1.The other template simply says that factorial of a number is that number times factorial minus 1.template<int T>struct factorial { enum { value = factorial<T - 1>::value * T };};Since there is really no "calling" in the classic sense, the template instantiates itself with a template argument equal to T-1 calculated at compile time.P.S. The warning shows that factorial of 34 overflows 32-bit integer. 这篇关于阶乘 T - 1 的含义在模板定义中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-19 14:31
查看更多