mercredi 19 décembre 2018

How to get compile time error checking with real valued function arguments?

Is it possible use static_assert (or something similar) with function arguments that are real valued? What I am trying to do is the following. The arguments min and max will always be constant in my application. Ideally, I would like to use them as template parameters, but doing so isn't possible because they are real valued. The motivation for using static_assert is that I would like to get compile time error checking.

template <typename counts_t, typename real_t>
real_t counts2real(counts_t c, real_t min, real_t max)
{
  constexpr real_t cmin = std::numeric_limits<counts_t>::min();
  constexpr real_t cmax = std::numeric_limits<counts_t>::max();
  constexpr real_t cdelta = (cmax - cmin);

  // ERROR: non-constant condition for static assertion.
  static_assert(max > min, "max > min");

  real_t delta = (max - min);
  real_t p = (c - cmin) / cdelta;

  return (p * delta + min);
}

int16_t x = 0;
const float min = 10.0;
const float max = 5.0;

float xf = counts2real<int16_t,float>(x, min, max);

Aucun commentaire:

Enregistrer un commentaire