有哪些技术/ c++语言工具--提供编译时分支的特性?
第一次尝试枚举它们(我期待添加-更正):
发布于 2014-07-31 23:26:39
您可以使用模板布尔参数来消除运行时分支(在发布版本中消除了死代码)。
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分支预测器通常是非常好的,编译时分支可能没有什么区别。
发布于 2014-07-31 10:14:42
虽然不是严格地编译时分支,但您可以添加第四个选项:
4) C++ 宏
#if SOMETHING
...
#else
...
#endifhttps://stackoverflow.com/questions/25055879
复制相似问题