如何理解和修复递归模板实例化错误使用boostublas
How to understand and fix recursive template instantiation error using boost ublas?
我收到一个编译器错误
/Developer/boost/boost/numeric/ublas/expression_types.hpp:184:16: fatal error: recursive template instantiation exceeded maximum depth of 512
从clang++开始,或从g++4.2.1开始,使用>10GB内存进行不确定编译。
我试图创建一个辅助函数,从向量的每个元素中减去一个标量。一开始我一般性地考虑,我计划将特定的向量存储类型作为模板参数。话虽如此,我意识到我不知道如何在这一点上使定义同时适用于ublas
和std
向量(没有专门化)。但我仍然想知道发生了什么/我的编译问题的原因是什么?
当符合boost库时,下面的代码很容易证明这个问题,例如。g++ -I/path/boost bug_demo.cpp
boost或我的代码中有漏洞吗?
// demo code does not compiler, instead error for recursive template instantiation
//---------------------------------------------------------
#include <boost/numeric/ublas/vector.hpp>
namespace ublas = boost::numeric::ublas; // boost ublas will be the implementation for basic vector container
typedef ublas::vector<double> DVEC; // double vector shorthand
// ********* problem function ***********
template <typename vec_t, typename scalar_t>
vec_t operator-( const vec_t & vec, scalar_t scalar )
{
ublas::scalar_vector<scalar_t> scalar_v(vec.size(), scalar);
return vec - scalar_v;
}
// this non-template version works fine.
/* DVEC operator-( const DVEC & vec, double scalar )
{
ublas::scalar_vector<double> scalar_v(vec.size(), scalar);
return vec - scalar_v;
}
*/
DVEC vectorFunc( const DVEC& x )
{
double bnew=0.0;
DVEC x_bnew;
x_bnew = operator-(x,bnew);
return x_bnew;
}
int main()
{
DVEC inputVector(2);
inputVector[0] = 1.0; inputVector[1] = 2.0;
DVEC output = vectorFunc( inputVector );
return 0;
}
operator - ()
函数在执行vec - scalar_v
时通过调用自身来设置无限模板实例化递归。虽然参数类型的名称是scalar_t
,但这只是一个名称,它可以匹配任何类型,包括scalar_vector<scalar_t>
。
因此,线路xbnew = operator - (x, bnew)
将导致的实例化
operator - <DVEC, double>()
该操作员模板中的最后一行将依次导致的实例化
operator - <DVEC, scalar_vector<double>>()
然后,同一操作员模板中的最后一行将导致的实例化
operator - <DVEC, scalar_vector<scalar_vector<double>>>()
依此类推,直到编译器达到最大实例化递归深度。
相关文章:
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 错误的cv::face FacemarkLBF实例化
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- gcc出现不明确的模板实例化错误
- 尝试实例化模板类的对象时出现"No Matching Constructor"错误
- 无法实例化抽象类错误
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?
- 模板实例化分析错误
- unique_ptr 使用尚未定义的参数进行实例化不会导致错误
- 与模板实例化相关的编译错误
- 从模板实例化/类型推断中查找错误消息的实际来源
- 类模板实例化错误
- 错误 C2908:显式专用化; 已被实例化
- C++11 列出 push_back() 实例化错误
- 如何修复错误C2259:无法实例化抽象类
- 使用非量表类型实例化模板时修复编译错误
- 由于命名空间而导致的对象实例化错误
- 无法在好友函数中实例化类?我没有得到在范围错误中声明
- 实例化对象时如何修复分段故障错误
- 将 SFINAE 上下文中不正确的模板实例化的硬错误转变为软错误