什么被认为是编译时分支?
What's considered to be compile time branching ?
提供编译时分支的技术/c++语言工具-特性是什么?
第一次尝试枚举它们(我期待添加-更正):
-
重载解析:例如选择适合所提供参数的"最佳"版本
void F(X& arg); void F(X&& arg);
-
模板专门化:创建针对"特殊参数"运行的代码——这是模板元编程和编译时递归的关键技术
template<int N> struct A { /* implementation */ }; template<> struct A<0> { /* specific code */ };
-
SFINAE,表达式sfinae:(1)的一个特例,它为条件接口提供了工具。
template<class C, class F> auto test(C c, F f) -> decltype((c->*f)(), void()); // 'C' is pointer type
您可以使用模板布尔参数来消除运行时分支(在发布版本中,死代码被消除)。
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>()
将比problem.CheckConverge<true>()
更快,并且该特性不会花费运行时分支。
然而,CPU分支预测器通常非常好,编译时分支可能没有区别。
虽然没有严格的编译时分支,但您可以添加作为第四个选项:
c++ 宏 #if SOMETHING
...
#else
...
#endif