1

I'm looking at some c++ audio DSP code from the Q audio dsp library https://github.com/cycfi/Q

i've noticed that in the file q_lib/include/q/synth/square.hpp the author has created a generator for bandlimited square waves using constexpr functions. (this is his function to return the current value)

constexpr float operator()(phase p, phase dt) const
  {
     constexpr auto middle = phase::max() / 2;
     auto r = p < middle ? 1.0f : -1.0f;

     // Correct rising discontinuity
     r += poly_blep(p, dt);

     // Correct falling discontinuity
     r -= poly_blep(p + middle, dt);

     return r;
  }

I'm trying to work out if there is any functional benefit to this since, for many use-cases, phase p and phase dt can't be evaluated at compile time, does this mean the function just turns into a normal non-const one? or is there still some other benefit apart from it being const function when p & dt are constant?

  • 4
    Welcome to StackOverflow! There are similar questions to this one, you can search for it in the database. Short answer: a function marked `constexpr` may be used in `constexpr` context (e.g. all parameters are `constexpr` as well) but if it is not - it will be used as regular function. The author of the function cannot foresee all the possible contexts of how/where the function will be used, so sometimes it's better to mark a function `constexpr` – Quarra Sep 23 '20 at 06:02
  • thanks for the response! So then why not just declare almost everything constexpr all the time just in case the compiler finds a case where they are const? – DrOfDissonance Sep 23 '20 at 06:11
  • 2
    See https://stackoverflow.com/questions/35309115/why-constexpr-is-not-the-default-for-all-function. Most important notes: 1) `constexpr` influences how template behaves 2) not everything is allowed to be `constexpr` (which is changing as well in newer versions of c++) 3) it is a part of method API: it is in some ways similar to `noexcept` - a strong promise to the caller that cannot be always maintained – Quarra Sep 23 '20 at 06:28

0 Answers0