简体   繁体   English

可变参数模板调用函数

[英]variadic template to call a function

I am trying to write a teamplate function that looks like this: 我正在尝试编写一个如下所示的teamplate函数:

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. 我认为您可以从中推断出适当的...语法(在参数列表中的class...之后,但在arg...之后)中用于在调用站点解包参数。

The std::forward is to distinguish between lvalues and rvalues. std::forward用于区分左值和右值。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM