如何编译期递归求和?

/** Compute the sum of elements of a vector */
template <unsigned int N>
class Series
{
    typedef int Vector[10];
public:
    static double Compute(Vector & vector)
    {
        return vector[N-1] + Series<N-1>::Compute( vector ); // recursion
    }
private:
};
double Series<1>::Compute(Vector & vector) // Specialization for terminating the recursion
{
    return vector[0];
}
int main()
{
  double sum;
  int values[10];
  sum = Series<10>::Compute(values);
  return 0;
}
posted @ 2020-04-13 15:27  學海無涯  阅读(194)  评论(0编辑  收藏  举报