Вопрос

I am trying to write a teamplate function that looks like this:

template<T FuncPtr, Params...>
void CallFunction(Params...)
{
    FuncPtr(Params...);
}

example usage:

typedef void (__stdcall* Test_t)(int a1, bool a2, char* a3);
Test_t fn = ....; //pointer obtained somehow

CallFunction<fn>(10, true, "Hello");

Is something like that possible? I dont know how to work with the parameter pack to have it unpacked so each member of the pack servers as a parameter.

Это было полезно?

Решение

I would suggest a minor rewrite into something like this:

#include <iostream>

template<class Fun, class... Args>
void CallFunction(Fun fun, Args&&... args)
{
    fun(std::forward<Args>(args)...);
}

void fn(int a1, bool a2, char const* a3)
{
    std::cout << a1 << a2 << a3;    
}

int main() 
{
    CallFunction(fn, 10, true, "Hello");
}

Live Example. I think you can deduce from this the proper ... syntax (after class... in the paramter list, but after arg... for unpacking arguments at the call site.

The std::forward is to distinguish between lvalues and rvalues. It's also better in general to use argument deduction by passing the function pointer (or callable object in general) as a regular function argument, rather than as an explicit template argument.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top