Im doing some image functions, which have lots of repetitive code, such as:
int r,sr;
int g,sg;
int b,sb;
int a,sa;
...
for(...){
sr += input[posin+0];
sg += input[posin+1];
sb += input[posin+2];
sa += input[posin+3];
}
...
output[posout+0] = sr;
output[posout+1] = sg;
output[posout+2] = sb;
output[posout+3] = sa;
How can i use templates to do this from the above code:
int r,sr;
int g,sg;
int b,sb;
...
for(...){
sr += input[posin+0];
sg += input[posin+1];
sb += input[posin+2];
}
...
output[posout+0] = sr;
output[posout+1] = sg;
output[posout+2] = sb;
or etc, depending on a value i give to the function? I could simply add if() in the loops, but that will slow down the function. So, i want to 开发者_高级运维cut parts of the code depending on the BytesPerPixel value i give to the function, how?
Also, the BytesPerPixel value should become a const inside the function, so if i use it somewhere and its value is 3, the calculation a*BytesPerPixel would become a*3. i want this to happen because it will make it faster, and multiplication with 4 or 2 or 1 will be even faster after compiler optimizes it.
Both of those can easily be reduced to:
int values[N];
// ...
for (...) {
for (int i(0); i < N; ++i) {
values[i] += input[posin + i];
}
}
for (int i(0); i < N; ++i) {
output[posout + i] = values[i];
}
N
can be provided as a nontype template parameter; for example:
template <unsigned N>
void f() {
// ...
}
精彩评论