Boost多精度:递归模板实例化超过最大长度256
Boost multiprecision : Recursive template instantiation exceeded maximum length 256
试图用boost的多精度数字玩一点,我得到了以下错误
In file included from main.cpp:1:
In file included from /usr/include/boost/multiprecision/cpp_int.hpp:12:
In file included from /usr/include/boost/multiprecision/number.hpp:16:
In file included from /usr/include/boost/type_traits/is_signed.hpp:15:
In file included from /usr/include/boost/type_traits/is_enum.hpp:14:
In file included from /usr/include/boost/type_traits/intrinsics.hpp:149:
/usr/include/boost/type_traits/is_reference.hpp:32:19: fatal error: recursive template instantiation exceeded maximum
depth of 256
接着是许多带有实例化错误签名的行。编译以下代码时出现问题:
#include<boost/multiprecision/cpp_int.hpp>
using big_int = boost::multiprecision::cpp_int;
big_int getOne(big_int){ return (big_int) 1;}
template<typename T, typename U>
T fastPowMod(T a, U b, T p){
if(b==0)
return getOne(a);
if(b%2 != 0){
return (a*fastPowMod(a,b-1,p))%p;
}
else{
T aux = fastPowMod(a,b/2,p);
return (aux*aux)%p;
}
}
int main(){
std::cout << fastPowMod<big_int,big_int>(108041234,180611234, 81243) std::endl;
}
带有
clang++ -std=c++11 main.cpp
我不知道为什么会发生这种情况,因为当用正则整数实例化时,这段代码编译得非常好。
编辑:我自己回答。永远记住,在处理模板和递归时要显式!
template<typename T, typename U>
T fastPowMod(T a, U b, T p){
if(b==0)
return getOne(a);
if(b%2 != 0){
return (a*fastPowMod<T,U>(a,b-1,p))%p;
}
else{
T aux = fastPowMod<T,U>(a,b/2,p);
return (aux*aux)%p;
}
}
您的解决方法缺乏理解。
问题是编译器返回延迟求值表达式模板。这导致递归调用为fastPowMod
中的每个递归级别无限地实例化不同的实例化。
建议的修复程序通过强制对递归调用的参数进行求值来禁用它。
等效地,您可以完全禁用ET:
using big_int = bmp::number<bmp::cpp_int::backend_type, bmp::et_off>;
在这种特殊情况下,可能希望考虑将递归变形为迭代,您或编译器可能会一次展开一些迭代。通过这种方式,可以保留懒惰评估带来的好处。
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 模板化类构造函数的模板实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 受约束的成员函数和显式模板实例化
- C++ 具有双精度和长双精度的显式模板实例化
- Boost多精度:递归模板实例化超过最大长度256