What is considered a fork in compilation time?

What are the C ++ methods / language tools that provide for branching over compilation time?


First attempt to list them (I expect add-fix):

  • Overload resolution : for example, choosing the “best” version matches the arguments provided

    void F(X& arg); void F(X&& arg); 
  • Template Specialization : Creating Code That Runs for “Special Arguments” - A Method Important for Metaprogramming a Template and Compiling Time Recursion

     template<int N> struct A { /* implementation */ }; template<> struct A<0> { /* specific code */ }; 
  • SFINAE and sfinae : a special case (1) that provides tools for conditional interfaces.

     template<class C, class F> auto test(C c, F f) -> decltype((c->*f)(), void()); // 'C' is pointer type 
+6
source share
2 answers

You can use boilerplate logic parameters to eliminate runtime fork (excluding assembly if dead code is deleted).

 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 function will not cost without a break in runtime.

However, the processor branch predictor is generally very good, and branching at compile time may not matter.

+2
source

Although it is not strictly compile temporary branching, you can add as a fourth option:

4) C ++ Macros

  #if SOMETHING ... #else ... #endif 
+1
source

Source: https://habr.com/ru/post/973154/


All Articles