Stefan Berger
Stefan Berger

Reputation: 17

Recusion and Templates in C++

I try to compute derivatives using Tangent mode. I tried to implement it using recursion. I got the following problem: I got a recursion with Templates which compiles forever.

template <typename T>
void dern(int n, const T &x, T &dy)
{
  using DCO_T = typename dco::gt1s<T>::type;
  DCO_T _x, _y;
  dco::value(_x) = x;
  dco::derivative(_x) = 1;
  if (n > 1)
  {
    dern(--n, _x, _y);
  }
  else
  {
    f(_x, _y);
  }
  dy = dco::derivative(_y);
}

if I try to write them out it works perfectly fine:

template <typename T>
void der1(const T &x, T &dy)
{
  using DCO_T = typename dco::gt1s<T>::type;
  DCO_T _x, _y;
  dco::value(_x) = x;
  dco::derivative(_x) = 1;
  f(_x, _y);
  dy = dco::derivative(_y);
}

template <typename T>
void der2(const T &x, T &dy)
{
  using DCO_T = typename dco::gt1s<T>::type;
  DCO_T _x, _y;
  dco::value(_x) = x;
  dco::derivative(_x) = 1;
  der1(_x, _y);
  dy = dco::derivative(_y);
}

template <typename T>
void der3(const T &x, T &dy)
{
  using DCO_T = typename dco::gt1s<T>::type;
  DCO_T _x, _y;
  dco::value(_x) = x;
  dco::derivative(_x) = 1;
  der2(_x, _y);
  dy = dco::derivative(_y);
}

template <typename T>
void der4(const T &x, T &dy)
{
  using DCO_T = typename dco::gt1s<T>::type;
  DCO_T _x, _y;
  dco::value(_x) = x;
  dco::derivative(_x) = 1;
  der3(_x, _y);
  dy = dco::derivative(_y);
}

My supervisor thinks it doesn't work because of the template. Does anyone know a fix?

Upvotes: 0

Views: 76

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16448

n should be a compile time parameter passed as template argument.

template <int n, typename T>
void dern(const T &x, T &dy)
{
  using DCO_T = typename dco::gt1s<T>::type;
  DCO_T _x, _y;
  dco::value(_x) = x;
  dco::derivative(_x) = 1;
  if constexpr (n > 1) {
    dern<n - 1>(_x, _y);
  } else {
    f(_x, _y);
  }
  dy = dco::derivative(_y);
}

A compile time recursion can't depend on a runtime variable.

Call it with, e.g.

dern<4>(x, y);

Upvotes: 3

Related Questions