如何理解和修复递归模板实例化错误使用boostublas

How to understand and fix recursive template instantiation error using boost ublas?

本文关键字:错误 实例化 boostublas 何理解 递归      更新时间:2023-10-16

我收到一个编译器错误

/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内存进行不确定编译。

我试图创建一个辅助函数,从向量的每个元素中减去一个标量。一开始我一般性地考虑,我计划将特定的向量存储类型作为模板参数。话虽如此,我意识到我不知道如何在这一点上使定义同时适用于ublasstd向量(没有专门化)。但我仍然想知道发生了什么/我的编译问题的原因是什么?

当符合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>>>()

依此类推,直到编译器达到最大实例化递归深度。