c++ - 如何使用 C++ 模板根据函数参数值添加代码片段?

标签 c++ visual-studio-2008 templates

我在做一些图片功能,里面有很多重复的代码,比如:

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;

我如何使用模板从上面的代码中做到这一点:

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;

或者等等,取决于我给函数的值?我可以简单地在循环中添加 if() ,但这会减慢函数的速度。所以,我想根据我赋予函数的 BytesPerPixel 值来剪切部分代码,如何实现?

另外,BytesPerPixel 的值应该在函数内部变成常量,所以如果我在某处使用它并且它的值为 3,计算 a*BytesPerPixel 就会变成 a*3。我希望发生这种情况,因为它会使速度更快,并且在编译器优化后与 4 或 2 或 1 相乘会更快。

最佳答案

这两个都可以很容易地简化为:

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 可以作为非类型模板参数提供;例如:

template <unsigned N>
void f() {
    // ...
}

关于c++ - 如何使用 C++ 模板根据函数参数值添加代码片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6916246/

相关文章:

C++ 将模板类型作为参数传递给错误

c++ - 为什么结构内部的对象初始化不同?

c - 使用 _sprintf_l 格式化 double 和数千个数

c++ - 将 void* 作为 std::unordered_map 的第二个模板参数是什么意思?

templates - 在 Angular 2 的 html 模板中引用服务是一种好习惯吗?

visual-studio-2008 - 如何将所有类提取到单独的文件中?

c++ - C++ 的压缩库

c++ - 有什么办法可以将这个函数分开并插入空格吗?

c++ - 关于绘图算法的好书,最好是 C 或 C++

visual-studio-2008 - 使用单个工作区的 TFS 多个用户