我可以使用一些代码作为 C++ 模板的参数吗? (不添加函数调用)

Can I use a bit of code as a parameter into a C++ template? (Without adding a function call)

我在一个函数上有几个对时间敏感的变体,所以我希望编写一个模板,只更改几行不同的代码。由于存在速度压力,我试图避免额外的函数调用。

以前使用预处理器我会写:

// code.inl
void FUNC_NAME
{
    a = 1;
    BIT_OF_CODE
    b = 2;
}

// program.cpp
#define FUNC_NAME Func1
#define BIT_OF_CODE c = 3;
#include "code.inl"
#undef BIT_OF_CODE 

#define FUNC_NAME Func2
#define BIT_OF_CODE c = 999;
#include "code.inl"

避免重复两个函数的样板部分:

void Func1
{
    a = 1; // Common declarations and processing
    c = 3;
    b = 2; // More common processing
}
void Func2
{
    a = 1;
    c = 999; // Switched out code uses lots of variables in scope
    b = 2;
}

我会考虑内联函数 - 但理想情况下,我会拥有类似 lambda 的东西,它可以使用所有局部变量(同时进行优化而无需更多函数调用)。

模板参数是否有一些技巧可以让我简单地注入一些代码?或者也许这仍然是预处理器的工作?

我喜欢模板方法,因为我有更多的变化点,可能的功能数量大大增加,我希望它们都单独编译和优化。

为什么不呢:

#include <stdio.h>
int a, b, c;

template <int N>
void func(){
    a = 1;
    if(N==1){
            c = 3;
#include "code1.inl"
    }else if(N==2){
            c = 999;
#include "code2.inl"
    }
    b = 2;
}

int main(){
    printf("a=%d;b=%d;c=%d\n", a, b, c);
    func<1>();
    printf("a=%d;b=%d;c=%d\n", a, b, c);
    func<2>();
    printf("a=%d;b=%d;c=%d\n", a, b, c);
    func<3>();
    printf("a=%d;b=%d;c=%d\n", a, b, c);
    return 0;
}

给出:

a=0;b=0;c=0
a=1;b=2;c=3
a=1;b=2;c=999
a=1;b=2;c=999

检查: 如果你用gcc -O0编译,你可以在"nm"

中看到函数
00000000000011fb W _Z4funcILi1EEvv
0000000000001224 W _Z4funcILi2EEvv
000000000000124d W _Z4funcILi3EEvv

但是如果你用-O1编译它,你就看不到它们了,所以它们被优化掉了。