Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's considered to be compile time branching ? [duplicate]

What are the techniques / c++ language facilities-features that provide compile time branching?


A first attempt to enumerate them (I'm expecting additions-corrections) :

  1. Overload resolution : Eg picking the version of the "best" suits the provided arguments

    void F(X& arg);
    void F(X&& arg); 
    
  2. 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 */ };
    
  3. 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
    
like image 629
Nikos Athanasiou Avatar asked Jul 31 '14 09:07

Nikos Athanasiou


2 Answers

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.

like image 69
ThreeStarProgrammer57 Avatar answered Nov 06 '22 23:11

ThreeStarProgrammer57


Although not strictly compile time branching you could add as fourth option:

4) C++ Macros

  #if SOMETHING
    ...
  #else
    ...
  #endif
like image 37
101010 Avatar answered Nov 06 '22 23:11

101010