0

so I have a template function:

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();
}

In the function test I now want to call other different functions, not only someFunc, which have different parameters. Like this:

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 should be like a list of arguments, all of which can be different types. This list I want to pass to the func. That’s what it would look like:

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);
}

Is that possible? If not, is there any other way?

1 Answers1

1

You can do this via Parameter pack. It folds the Arguments that you have given.

I wrote a small example. I hope it helps you.

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);
}

The function uses trailing return type. test function has two overloads. One for the temporary object that uses perfect forwarding, std::forward, to avoid unnecessary copy costs. Other ones for lvalue objects.

Murat Hepeyiler
  • 430
  • 3
  • 12