为什么这个乘法模板代码会导致溢出
Why does this multiply template code cause overflow?
我在这里有一个模板,它像这样相乘:
-
如果我传入
2
和5
作为模板参数,它将生成5个数字乘以自己从2
开始 -
multiply_n_times<2, 5>
=pack<2, 4, 16, 256>
这是我尝试过的
template<int Value, int Count, int... Is>
struct multiply_n_times : multiply_n_times<Value*Value, Count-1, Is..., Value> { };
template<int Value, int... Is>
struct multiply_n_times<Value, 0, Is...> : pack<Is...> { };
当我实例化它时,我得到这个错误:
main.cpp: In instantiation of 'struct multiply_n_times<65536, 1, 2, 4, 16, 256>':
main.cpp:15:8: recursively required from 'struct multiply_n_times<4, 4, 2>'
main.cpp:15:8: required from 'struct multiply_n_times<2, 5>'
main.cpp:39:17: required from here`
main.cpp:15:8: error: overflow in constant expression [-fpermissive]
struct multiply_n_times : multiply_n_times<Value*Value, Count-1, Is..., Value> { };
我在这里做错了什么?
第一个参数被丢弃的最后一个递归存在溢出。
所以跳过它:
template<int Value, int... Is>
struct multiply_n_times<Value, 1, Is...> :
pack<Is..., Value>
{ };
现在我们从不计算不使用的Value*Value
。
如果您需要0
的正方形长度列表,请保留0
专门化。
在实例化中,Value
自身乘以5次
2 * 2 -> 4,4 * 4 -> 16,16 * 16 -> 256,256 * 256 -> 65536和65536 * 65536 -> overflow
如果您想在第四步停止,那么您需要使用multiply_n_times<2, 4>
或为Count = 1
提供专门化,而不是Count = 0
。
@user2040251有正确的答案,您的乘法导致int值溢出。更一般地说,对于Value = v
和Count=n
的初始实例化,您可以期望达到v^(2^n)。如果您将代码更改为在Count=1
处停止,那么您将到达v^(2^(n-1))。
相关文章:
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 代码仅在2个功能实现中的1个中溢出
- 堆缓冲区溢出随机发生。对于一个简单的代码?(我是C++新手)
- 为什么此代码不会导致缓冲区溢出
- 缓冲区溢出的外壳代码如何生成
- 为什么编写的代码在执行时出现溢出错误
- 内存将被代码中的溢出覆盖
- 0x00363A09处出现未处理的异常,堆栈cookie检测代码检测到基于堆栈的缓冲区溢出
- 为什么Visual Studio说如果我的程序中没有编写任何数据结构代码,我就会出现堆栈溢出?C++
- 一些人发现此代码存在溢出问题.小的数字是非常负的
- 为什么这C++代码会触发堆栈溢出
- 堆栈溢出错误 c++.我如何修改/修复此代码以摆脱此问题
- 为什么我的递归代码会导致堆栈溢出错误
- 简单的程序集代码会产生缓冲区溢出
- 为什么在Visual Studio 2012上的代码分析中,此代码会发出缓冲区溢出警告(C6385/C6386)
- 遗留代码似乎溢出了,我不确定
- 如何避免此代码中的堆栈溢出(递归函数)
- 为什么这个乘法模板代码会导致溢出
- 如何处理c++代码中可能出现的整数溢出?
- 此代码如何产生无符号整数溢出