What are the techniques / c++ language facilities-features that provide compile time branching?
A first attempt to enumerate them (I'm expecting additions-corrections) :
Overload resolution : Eg picking the version of the "best" suits the provided arguments
void F(X& arg);
void F(X&& arg);
Template specialization : Creating code that runs for "special arguments" - a technique crucial for template metaprogramming and compile time recursion
template<int N> struct A { /* implementation */ };
template<> struct A<0> { /* specific code */ };
SFINAE & expression sfinae : A special case of (1) that provides the tools for conditional interfaces.
template<class C, class F>
auto test(C c, F f) -> decltype((c->*f)(), void()); // 'C' is pointer type
You can use template Boolean parameters to eliminate run time branching (in release build dead code is eliminated).
template <bool computeMaxNorm = false>
bool CheckConvergence() {
if (computeMaxNorm) this->residual_max_norm = 0;
for (size_t i = 0, I = this->X.Count(); i < I; ++i) {
double abs_res = abs(this->F_X[i]);
if (abs_res > this->convergenceCriterion) {
this->isConverged = false;
if (!computeMaxNorm) return false;
}
if (computeMaxNorm) {
if (abs_res > this->residual_max_norm) this->residual_max_norm = abs_res;
}
}
return this->isConverged = true;
}
problem.CheckConverge<false>()
will be faster than problem.CheckConverge<true>()
, and this feature will cost no run time branching.
However the CPU branch predictor is usually very good and compile-time branching may make no difference.
Although not strictly compile time branching you could add as fourth option:
4) C++ Macros
#if SOMETHING
...
#else
...
#endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With