在模板函数中包含不变假设 [英] Including an invariant assumption in a template function
问题描述
考虑一个典型的有限差分应用程序:
Consider a typical finite difference application:
// assuming T_size > 2
void process_T(double *T0, double *T, const int &T_size, bool periodic) {
for (int i = 0; i < T_size; ++i) {
double sum = 0;
double base = T0[i];
if (i > 0) sum += (T0[i-1]-base);
if (i < 0) sum += (T0[i+1]-base);
if (periodic) {
if (i == 0) sum += (T0[T_size-1]-base);
if (i == T_size-1) sum += (T0[0]-base);
} else {
if (i == 1 || i == T_size-1) sum += 0.5*(T0[i-1]-base);
if (i == 0 || i == T_size-2) sum += 0.5*(T0[i+1]-base);
}
T[i] = T0[i] + sum * 0.08; // where 0.08 is some magic number
}
}
periodic
的检查是循环不变的,但是由于仅在运行时才知道,因此每次都会产生条件检查费用.我可以创建一个假设其中一种情况的专用函数,但是要维护通用基数会很麻烦,尤其是在三维问题中,它会增长到8个函数(周期性:none,x,y,z, xy,xz,yz,xyz)来考虑所有组合.
The check for periodic
is loop-invariant, but since is only known at run-time, the conditional check cost is incurred everytime. I could create a specialized function which assumes one of the cases, but it would be cumbersome to maintain the common base, especially in case of three-dimensional problem where it would grow to 8 functions (periodicity: none, x, y, z, xy, xz, yz, xyz) to consider all combinations.
是否可以通过元编程解决此问题?
Is it possible to solve this problem via metaprogramming?
P/S:分支预测器可以相应地对其进行优化吗?
P/S: can the branch predictor optimize this accordingly?
推荐答案
是的,您可以拥有
enum Periodicity
{
PERIODICITY_NONE,
PERIODICITY_X,
PERIODICITY_Y
// etc
};
然后
template <Periodicity P>
void process_T(double* T0, double* T, const int& T_size)
{
if (P == PERIODICITY_NONE) // ... do something
if (P == PERIODICITY_X) // ... do something else
// Common code
}
任何体面的优化编译器都可以在编译时执行检查,并且可以消除任何无效代码(即使在-O0
上,g ++似乎也可以这样做).
Any decent optimising compiler would be able to perform the check at compile time, and would eliminate any dead code (g++ appears to do this even at -O0
).
这篇关于在模板函数中包含不变假设的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!