具有不同参数数量和类型的模板函数

Template function with different amount and type of parameters

所以我有一个模板函数:

int someFunc(int num) {

    int a = num / 2;
    int b = num + 10;
    return a + num / b + b;
}

template<typename Type, typename Function>
Type test() {
    Function func = (Function)&someFunc;
    return func();
}

在函数 test 中,我现在想调用其他不同的函数,而不仅仅是 someFunc,它们具有不同的参数。像这样:

template<typename Type, typename Function>
    Type test(args) {
        Function func = (Function)&someFunc; //This is later replaced with an variable, that contains a address to a different function
        return func(args);
    }

args 应该像一个参数列表,所有参数都可以是不同的类型。我要将此列表传递给 func。这就是它的样子:

typedef int(__cdecl* tSomeFunc)(int, int, BYTE*);
int i = test<int, tSomeFunc>(4, 6, "Hey");

template<typename Type, typename Function>
Type test(argument list that accepts all the arguments given above) {
    Function func = (Function)&someFunc;
    return func(argument list);
}

这可能吗?如果不行,还有其他办法吗?

您可以通过 Parameter pack 执行此操作。它折叠您提供的参数。

我写了一个小例子。希望对你有帮助。

template<typename Func, typename... Args>
auto test(Func f, Args&... args)
{
    return f(args...);
}

template<typename Func, typename... Args>
auto test(Func f, Args&&... args)
{
    return f(std::forward<Args>(args)...);
}

double func(double a, float b)
{
    return a * b;
}


int foo(int a, int b, int c)
{
    return a + b + c +5;
}

int main()
{
    std::cout << test(foo, 5, 10 , 20) << "\n";
    std::cout << test(func, 20.5, 100.4) << "\n";
    double x = 100.31;
    double y = 23.52;
    std::cout << test(func, x, y);
}

函数使用trailing return typetest 函数有两个重载。一个用于使用 perfect forwardingstd::forward 的临时对象,以避免不必要的复制成本。其他用于左值对象。