I couldn’t find the answer through searching, so next step is asking. Say I have some code like this:
template<class Int>
inline Int onbit(Int value, int n) {
return value | (static_cast<Int>(1) << n);
}
If I call the code, like this onbit(A, 4), would the constant 4 be propagated through and optimized, or should I make it a template (template<int n, class Int>) so that it would be constant. Is C++0x constexpr neccessary here and if so, how exactly should I use it (should int n be const or constexpr?).
I know that constexpr would work with constant parameters, but would it partially be optimized if part of the parameters were constant and part were variable?
Summary: Is it possible for a function (it has to be inline right?) to be partially optimized with constant propagation, and, if so, what are the requirements to do it?
Even as I am writing this I am thinking that an inline function call would propagate constants…
You can’t guarantee that all compilers will optimize this code, although most modern compilers (MSVC and gcc) will, at least in most cases (it depends on the context) without regard to const-ness, since the function is so simple.
On the other hand, you can’t guarantee that any compiler will optimize it strictly better when you do use const.
So, if optimization is important for you, in all cases the only answer is – check your assembly in the cases when it matters. Your compiler may optimize it in one file, but not the other (e.g. when this function is called deep inside a convoluted template, it is conceivable though improbable that your compiler’s optimizer will give up and not optimize it in some cases).
I believe you should rely on const only when it’s needed for compile-time checks, and you should rely on checking generated assembly when it’s needed for run-time efficiency.