什么是技术/ c ++语言工具 - 提供编译时分支的功能?
首次尝试枚举它们(我期待添加更正):
重载决议:例如,选择“最佳”版本适合提供的参数
void F(X& arg);
void F(X&& arg);
模板专业化:创建为“特殊参数”运行的代码 - 一种对模板元编程和编译时间递归至关重要的技术
template<int N> struct A { /* implementation */ };
template<> struct A<0> { /* specific code */ };
SFINAE&amp;表达式sfinae :(1)的一个特例,为条件接口提供工具。
template<class C, class F>
auto test(C c, F f) -> decltype((c->*f)(), void()); // 'C' is pointer type
答案 0 :(得分:2)
您可以使用模板布尔参数来消除运行时分支(在发布版本中删除死代码)。
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分支预测器通常非常好,编译时分支可能没有区别。
答案 1 :(得分:1)
虽然不是严格编译时间分支,但您可以添加第四个选项:
4)C ++ 宏
#if SOMETHING
...
#else
...
#endif