将带有专用模板的 C++ 代码移植到 C 语言

Porting of C++ code with specialized templates to C language

我有很多非常相似的功能,比如

void someLargeFulction1(args)
{
    IDENTICAL CODE
    DIFFERENT CODE 1
    IDENTICAL CODE
}

//---------------------------//
//---------------------------//

void someLargeFulctionN(args)
{
    IDENTICAL CODE
    DIFFERENT CODE N
    IDENTICAL CODE
}

所有这些函数仅在DIFFERENT CODE N部分有所不同(这是一组浮点运算)。由于大多数 someLargeFulctionN 代码是相同的,我不会避免代码复制,因为这会使代码维护变得非常复杂。减少次数是我的主要目标。不幸的是,由于关键的性能影响,我无法将 DIFFERENT CODE 组织为函数调用并将此函数作为 someLargeFulction 参数传递 - DIFFERENT CODE 的执行速度比典型的函数调用快得多,不包括编译器调用内联。我不想将 someLargeFulctionN 组织为宏定义(但这是可能的解决方案)。

在C++编程语言中我有一个非常简单有用的解决方案——模板函数。我可以做类似的事情:

template <int N>
void someLargeFulction(args)
{
    IDENTICAL CODE
    differentCode<N>();
    IDENTICAL CODE
 }

并为所有变体专门化 differentCode() 函数。对于所有经过测试的编译器(g++、MVSC),它工作得很好!编译器总是内联一个 differentCode 调用,我有必要数量的 someLargeFulction 变体。问题是现在我需要将此代码移植到 С98。为了直接解决问题,我需要创建完整的 someLargeFulction 个副本,这是一个错误的决定。使用具有 someLargeFulction 实现的宏定义可以接受,但不可取。您还看到哪些其他选项?

类似于:

#include <stdio.h>

#define doIt(OP,a,b) do##OP(a,b)

#define performTmpl(OP,a,b,c) { for (int i=0; i<10; i++) a[i]=doIt(OP,b[i],c[i]); }

enum { ADD, SUB };

int doADD(int a,int b) { return a+b; }
int doSUB(int a,int b) { return a-b; }

int main() {
        printf("%d\n",doIt(ADD,5,4));
        printf("%d\n",doIt(SUB,5,4));

        int x[10], y[10]={1,2,3,4,5,6,7,8,9,10}, z[10]={1,1,1,1,1,1,1,1,1,1};
        performTmpl(ADD,x,y,z);
        for (int i=0; i<10; i++) printf("%d\n",x[i]);
}