The basic idea of constant expressions is to allow certain computations to takeplace at compile time--literally while your code compiles--rather than when theprogram itself is run. This has an obvious performance benefit: if something canbe done at compile time, it will be done once, rather than every time theprogram runs. Need to compute the value of a known constant like the sine orcosine of a specific, known-at-compile number? Sure, you could use the librarysin or cos function, but you'll pay the price of a function call at runtime.With constexpr, you can create a function that, at compile time, computes thevalue for you. Your user's CPU will never need to do any work at all forit!
Now, it's certainly true that if the operation can be computed at compile time, you could hard-code a constant. But doing that means that you lose flexibility if you later want to change the constant value--you have to recompute it, rather than just change an argument to a function.
Constexpr in actionIn order to get compile time processing, you need to use theconstext keyword on the function that you want to be able to compute at compiletime.
constexpr int multiply (int x, int y)View the Original article
Нема коментара:
Постави коментар