gpt4 book ai didi

c++ - 如何在不更改其余代码的情况下替换 C++ 模板以使其与 C 兼容?

转载 作者:行者123 更新时间:2023-12-01 22:34:04 31 4
gpt4 key购买 nike

我正在编写 C++ 编写的代码,并尝试将其转换为 C 以在嵌入式平台上构建。

我想知道如何有效地转换模板以在 C 中执行相同的功能而不更改其余代码。

这是我项目中的示例文件:

template <typename T,int width,int depth>
void relu(T arr[][width][depth],T layermap[][width][depth]){
for(int k=0;k<depth;k++)
{
for(int j=0;j<width;j++)
{
for (int i=0;i<width;i++)
{
/*max*/
layermap[i][j][k]=((arr[i][j][k]>0)? arr[i][j][k]:0);
}
}
}

}

最佳答案

此模板函数无法用宏替换,因为 C 预处理器无法推导出 width深度 值。我能建议的最好的办法是将部分代码移至 C 宏中,并在其上添加 C++ 模板包装器。这将保持与现有 C++ 代码的兼容性,但 C 代码必须手动传递宽度和深度:

// C header
#define crelu(arr, layermap, width, depth) do { \
for (int i=0;i<width;i++) \
for(int j=0;j<width;j++) \
for(int k=0;k<depth;k++) \
layermap[i][j][k]=((arr[i][j][k]>0)? arr[i][j][k]:0); \
} while(0)
// c++ header
template <typename T,int width,int depth>
void relu(T arr[][width][depth],T layermap[][width][depth]) {
crelu(arr, layermap, width, depth);
}

关于c++ - 如何在不更改其余代码的情况下替换 C++ 模板以使其与 C 兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60152884/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com